<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <title>JavaScript 面向对象程序设计、函数表达式和异步编程 | 净土</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="JavaScript 面向对象程序设计、函数表达式和异步编程，创建对象，继承，递归，闭包，块级作用域，私有变量，回调函数，Promise，Generator函数，async函数">
<meta property="og:type" content="article">
<meta property="og:title" content="JavaScript 面向对象程序设计、函数表达式和异步编程">
<meta property="og:url" content="http://howiefh.github.io/2015/08/28/javascript-oop-function-expression-and-async/index.html">
<meta property="og:site_name" content="净土">
<meta property="og:description" content="JavaScript 面向对象程序设计、函数表达式和异步编程，创建对象，继承，递归，闭包，块级作用域，私有变量，回调函数，Promise，Generator函数，async函数">
<meta property="og:updated_time" content="2015-09-01T03:35:47.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="JavaScript 面向对象程序设计、函数表达式和异步编程">
<meta name="twitter:description" content="JavaScript 面向对象程序设计、函数表达式和异步编程，创建对象，继承，递归，闭包，块级作用域，私有变量，回调函数，Promise，Generator函数，async函数">
  
    <link rel="alternative" href="/atom.xml" title="净土" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.ico">
  
  <link href="http://fonts.useso.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  <link rel="stylesheet" href="/css/style.css" type="text/css">
  
<script type="text/javascript">
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-40492061-1', 'auto');
ga('send', 'pageview');

</script>


  
<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "//hm.baidu.com/hm.js?56d2899c5e919fbf4a7b00de5d1c31dd";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>


</head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/" id="logo">净土</a>
      </h1>
      
        <h2 id="subtitle-wrap">
          <a href="/" id="subtitle">乐不在外而在心，心以为乐，则是境皆乐；心以为苦，则无境不苦。</a>
        </h2>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/">Home</a>
        
          <a class="main-nav-link" href="/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-github-link" class="nav-icon" href="https://github.com/howiefh" title="Github" target="_blank"></a>
        
        
          <a id="nav-rss-link" class="nav-icon" href="/atom.xml" title="RSS Feed" target="_blank"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="Search"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" results="0" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="http://howiefh.github.io"></form>
      </div>
    </div>
  </div>
</header>

      <div class="outer">
        <section id="main"><article id="post-javascript-oop-function-expression-and-async" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    
<a href="/2015/08/28/javascript-oop-function-expression-and-async/" class="article-date">
  <time datetime="2015-08-28T04:23:08.000Z" itemprop="datePublished">2015-08-28</time>
</a>


    
  <div class="article-category">
    <a class="article-category-link" href="/categories/JavaScript/">JavaScript</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      JavaScript 面向对象程序设计、函数表达式和异步编程
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
		
		<div id="toc" class="toc-article">
			<h2 class="toc-title"><span>Contents</span></h2>
		
			<ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#面向对象程序设计"><span class="toc-number">1.</span> <span class="toc-text">面向对象程序设计</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#属性类型"><span class="toc-number">1.1.</span> <span class="toc-text">属性类型</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#定义多个属性"><span class="toc-number">1.2.</span> <span class="toc-text">定义多个属性</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#读取属性的特性"><span class="toc-number">1.3.</span> <span class="toc-text">读取属性的特性</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#创建对象"><span class="toc-number">1.4.</span> <span class="toc-text">创建对象</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#工厂模式"><span class="toc-number">1.4.1.</span> <span class="toc-text">工厂模式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#构造函数模式"><span class="toc-number">1.4.2.</span> <span class="toc-text">构造函数模式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#原型模式"><span class="toc-number">1.4.3.</span> <span class="toc-text">原型模式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#组合使用构造函数模式和原型模式"><span class="toc-number">1.4.4.</span> <span class="toc-text">组合使用构造函数模式和原型模式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#动态原型模式"><span class="toc-number">1.4.5.</span> <span class="toc-text">动态原型模式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#寄生构造函数模式"><span class="toc-number">1.4.6.</span> <span class="toc-text">寄生构造函数模式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#稳妥构造函数模式"><span class="toc-number">1.4.7.</span> <span class="toc-text">稳妥构造函数模式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Class"><span class="toc-number">1.4.8.</span> <span class="toc-text">Class</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#constructor方法"><span class="toc-number">1.4.8.1.</span> <span class="toc-text">constructor方法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#实例对象"><span class="toc-number">1.4.8.2.</span> <span class="toc-text">实例对象</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#name属性"><span class="toc-number">1.4.8.3.</span> <span class="toc-text">name属性</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#class_表达式"><span class="toc-number">1.4.8.4.</span> <span class="toc-text">class 表达式</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#不存在变量提升"><span class="toc-number">1.4.8.5.</span> <span class="toc-text">不存在变量提升</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#严格模式"><span class="toc-number">1.4.8.6.</span> <span class="toc-text">严格模式</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#class的取值函数（getter）和存值函数（setter）"><span class="toc-number">1.4.8.7.</span> <span class="toc-text">class的取值函数（getter）和存值函数（setter）</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Class的Generator方法"><span class="toc-number">1.4.8.8.</span> <span class="toc-text">Class的Generator方法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Class的静态方法"><span class="toc-number">1.4.8.9.</span> <span class="toc-text">Class的静态方法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#new-target属性"><span class="toc-number">1.4.8.10.</span> <span class="toc-text">new.target属性</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Mixin模式的实现"><span class="toc-number">1.4.8.11.</span> <span class="toc-text">Mixin模式的实现</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#继承"><span class="toc-number">1.5.</span> <span class="toc-text">继承</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#原型链"><span class="toc-number">1.5.1.</span> <span class="toc-text">原型链</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#借用构造函数"><span class="toc-number">1.5.2.</span> <span class="toc-text">借用构造函数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#组合继承"><span class="toc-number">1.5.3.</span> <span class="toc-text">组合继承</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#原型式继承"><span class="toc-number">1.5.4.</span> <span class="toc-text">原型式继承</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#寄生式继承"><span class="toc-number">1.5.5.</span> <span class="toc-text">寄生式继承</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#寄生组合式继承"><span class="toc-number">1.5.6.</span> <span class="toc-text">寄生组合式继承</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Class的继承"><span class="toc-number">1.5.7.</span> <span class="toc-text">Class的继承</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#基本用法"><span class="toc-number">1.5.7.1.</span> <span class="toc-text">基本用法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#类的prototype属性和__proto__属性"><span class="toc-number">1.5.7.2.</span> <span class="toc-text">类的prototype属性和__proto__属性</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Extends_的继承目标"><span class="toc-number">1.5.7.3.</span> <span class="toc-text">Extends 的继承目标</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Object-getPrototypeOf()"><span class="toc-number">1.5.7.4.</span> <span class="toc-text">Object.getPrototypeOf()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#super关键字"><span class="toc-number">1.5.7.5.</span> <span class="toc-text">super关键字</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#实例的__proto__属性"><span class="toc-number">1.5.7.6.</span> <span class="toc-text">实例的__proto__属性</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#原生构造函数的继承"><span class="toc-number">1.5.8.</span> <span class="toc-text">原生构造函数的继承</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#函数表达式"><span class="toc-number">2.</span> <span class="toc-text">函数表达式</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#递归"><span class="toc-number">2.1.</span> <span class="toc-text">递归</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#闭包"><span class="toc-number">2.2.</span> <span class="toc-text">闭包</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#闭包与变量"><span class="toc-number">2.2.1.</span> <span class="toc-text">闭包与变量</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#关于_this_对象"><span class="toc-number">2.2.2.</span> <span class="toc-text">关于 this 对象</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#内存泄露"><span class="toc-number">2.2.3.</span> <span class="toc-text">内存泄露</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#模仿块级作用域"><span class="toc-number">2.3.</span> <span class="toc-text">模仿块级作用域</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#私有变量"><span class="toc-number">2.4.</span> <span class="toc-text">私有变量</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#静态私有变量"><span class="toc-number">2.4.1.</span> <span class="toc-text">静态私有变量</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#模块模式"><span class="toc-number">2.4.2.</span> <span class="toc-text">模块模式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#增强的模块模式"><span class="toc-number">2.4.3.</span> <span class="toc-text">增强的模块模式</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#异步操作"><span class="toc-number">3.</span> <span class="toc-text">异步操作</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#异步基本概念"><span class="toc-number">3.1.</span> <span class="toc-text">异步基本概念</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#回调函数"><span class="toc-number">3.2.</span> <span class="toc-text">回调函数</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Promise"><span class="toc-number">3.3.</span> <span class="toc-text">Promise</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Generator函数"><span class="toc-number">3.4.</span> <span class="toc-text">Generator函数</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#协程"><span class="toc-number">3.4.1.</span> <span class="toc-text">协程</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Generator函数的概念"><span class="toc-number">3.4.2.</span> <span class="toc-text">Generator函数的概念</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Generator函数的数据交换和错误处理"><span class="toc-number">3.4.3.</span> <span class="toc-text">Generator函数的数据交换和错误处理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#异步任务的封装"><span class="toc-number">3.4.4.</span> <span class="toc-text">异步任务的封装</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Thunk函数"><span class="toc-number">3.4.5.</span> <span class="toc-text">Thunk函数</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#参数的求值策略"><span class="toc-number">3.4.5.1.</span> <span class="toc-text">参数的求值策略</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Thunk函数的含义"><span class="toc-number">3.4.5.2.</span> <span class="toc-text">Thunk函数的含义</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#JavaScript语言的Thunk函数"><span class="toc-number">3.4.5.3.</span> <span class="toc-text">JavaScript语言的Thunk函数</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Thunkify模块"><span class="toc-number">3.4.5.4.</span> <span class="toc-text">Thunkify模块</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Generator_函数的流程管理"><span class="toc-number">3.4.5.5.</span> <span class="toc-text">Generator 函数的流程管理</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Thunk函数的自动流程管理"><span class="toc-number">3.4.5.6.</span> <span class="toc-text">Thunk函数的自动流程管理</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#co模块"><span class="toc-number">3.4.6.</span> <span class="toc-text">co模块</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#基本用法-1"><span class="toc-number">3.4.6.1.</span> <span class="toc-text">基本用法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#co模块的原理"><span class="toc-number">3.4.6.2.</span> <span class="toc-text">co模块的原理</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#基于Promise对象的自动执行"><span class="toc-number">3.4.6.3.</span> <span class="toc-text">基于Promise对象的自动执行</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#处理并发的异步操作"><span class="toc-number">3.4.6.4.</span> <span class="toc-text">处理并发的异步操作</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#async函数"><span class="toc-number">3.5.</span> <span class="toc-text">async函数</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#含义"><span class="toc-number">3.5.1.</span> <span class="toc-text">含义</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#async函数的实现"><span class="toc-number">3.5.2.</span> <span class="toc-text">async函数的实现</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#async_函数的用法"><span class="toc-number">3.5.3.</span> <span class="toc-text">async 函数的用法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#注意点"><span class="toc-number">3.5.4.</span> <span class="toc-text">注意点</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#与Promise、Generator的比较"><span class="toc-number">3.5.5.</span> <span class="toc-text">与Promise、Generator的比较</span></a></li></ol></li></ol></li></ol>
		
		</div>
		
        <p><a href="2015/08/28/javascript-grammar/">JavaScript 基本语法</a>，<a href="2015/08/28/javascript-reference-type/">JavaScript 引用类型</a>，<a href="2015/08/28/javascript-oop-function-expression-and-async/">JavaScript 面向对象程序设计、函数表达式和异步编程</a>三篇笔记是对《JavaScript 高级程序设计》和 <a href="https://github.com/ruanyf/es6tutorial/tree/5a5f9d8d492d0f925cbb6e09b10ebed9d2078d40" target="_blank" rel="external">《ECMAScript 6入门》</a>两本书的总结整理。</p>
<h1 id="面向对象程序设计">面向对象程序设计</h1><p>ECMA-262把对象定义为：“无序属性的集合，其属性可以包含基本值、对象或者函数。”严格来讲，这就相当于说对象是一组没有特定顺序的值。对象的每个属性或方法都有一个名字，而每个名字都映射到一个值。正因为这样（以及其他将要讨论的原因），我们可以把ECMAScript的对象想象成散列表：无非就是一组名值对，其中值可以是数据或函数</p>
<a id="more"></a>
<h2 id="属性类型">属性类型</h2><p>ECMAScript 中有两种属性:数据属性和访问器属性。</p>
<ol>
<li><p>数据属性<br> 数据属性包含一个数据值的位置。在这个位置可以读取和写入值。数据属性有4个描述其行为的特性。</p>
<ul>
<li>[[Configurable]]：表示能否通过 delete 删除属性从而重新定义属性，能否修改属性的特性，或者能否把属性修改为访问器属性。像前面例子中那样直接在对象上定义的属性，它们的这个特性默认值为true。</li>
<li>[[Enumerable]]：表示能否通过 for-in 循环返回属性。像前面例子中那样直接在对象上定义的属性，它们的这个特性默认值为true。</li>
<li>[[Writable]]：表示能否修改属性的值。像前面例子中那样直接在对象上定义的属性，它们的这个特性默认值为true。</li>
<li><p>[[Value]]：包含这个属性的数据值。读取属性值的时候，从这个位置读；写入属性值的时候，把新值保存在这个位置。这个特性的默认值为undefined。</p>
<p>像例子中那样直接在对象上定义的属性,它们的 [[Configurable]] 、 [[Enumerable]] 和 [[Writable]] 特性都被设置为 true ,而 [[Value]] 特性被设置为”Nicholas”。例如: <code>var person = { name: &quot;Nicholas&quot; };</code></p>
<p>要修改属性默认的特性，必须使用ECMAScript 5的Object.defineProperty()方法。这个方法接收三个参数：属性所在的对象、属性的名字和一个描述符对象。其中，描述符（descriptor）对象的属性必须是：configurable、enumerable、writable 和 value。设置其中的一或多个值，可以修改对应的特性值。</p>
<figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">var <span class="keyword">person</span> = &#123;&#125;;</span><br><span class="line">Object.defineProperty(<span class="keyword">person</span>, <span class="string">"name"</span>, &#123;</span><br><span class="line">  writable: false,</span><br><span class="line">  value: <span class="string">"Nicholas"</span></span><br><span class="line">&#125;);</span><br><span class="line">alert(<span class="keyword">person</span>.name); //<span class="string">"Nicholas"</span></span><br><span class="line"><span class="keyword">person</span>.name = <span class="string">"Greg"</span>;</span><br><span class="line">alert(<span class="keyword">person</span>.name); //<span class="string">"Nicholas"</span></span><br></pre></td></tr></table></figure>
<p>name属性的值是不可修改的，如果尝试为它指定新值，则在非严格模式下，赋值操作将被忽略；在严格模式下，赋值操作将会导致抛出错误。</p>
<p>把configurable设置为false，表示不能从对象中删除属性。如果对这个属性调用delete，则在非严格模式下什么也不会发生，而在严格模式下会导致错误。而且,一旦把属性定义为不可配置的,就不能再把它变回可配置了。此时,再调用 Object.defineProperty() 方法修改除 writable 之外的特性</p>
<p>可以多次调用Object.defineProperty()方法修改同一个属性，但在把configurable特性设置为false之后就会有限制了。 在调用Object.defineProperty()方法时，如果不指定，configurable、enumerable和writable特性的默认值都是false。</p>
</li>
</ul>
</li>
<li><p>访问器属性<br> 访问器属性不包含数据值；它们包含一对儿getter和setter函数（不过，这两个函数都不是必需的）。在读取访问器属性时，会调用 getter函数，这个函数负责返回有效的值；在写入访问器属性时，会调用setter函数并传入新值，这个函数负责决定如何处理数据。访问器属性有如下4个特性。</p>
<ul>
<li>[[Configurable]]：表示能否通过 delete 删除属性从而重新定义属性，能否修改属性的特性，或者能否把属性修改为数据属性。对于直接在对象上定义的属性，这个特性的默认值为true。</li>
<li>[[Enumerable]]：表示能否通过 for-in 循环返回属性。对于直接在对象上定义的属性，这个特性的默认值为true。</li>
<li>[[Get]]：在读取属性时调用的函数。默认值为undefined。</li>
<li><p>[[Set]]：在写入属性时调用的函数。默认值为undefined。</p>
<p>访问器属性不能直接定义，必须使用Object.defineProperty()来定义。</p>
<figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> book = &#123;</span><br><span class="line">  _year: <span class="number">2004</span>,</span><br><span class="line">  edition: <span class="number">1</span></span><br><span class="line">&#125;;</span><br><span class="line">Object.defineProperty(book, <span class="string">"year"</span>, &#123;</span><br><span class="line">  <span class="keyword">get</span>: <span class="function"><span class="keyword">function</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>._year;</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="keyword">set</span>: <span class="function"><span class="keyword">function</span><span class="params">(newValue)</span></span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (newValue &gt; <span class="number">2004</span>) &#123;</span><br><span class="line">      <span class="keyword">this</span>._year = newValue;</span><br><span class="line">      <span class="keyword">this</span>.edition += newValue - <span class="number">2004</span>;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br><span class="line">book.year = <span class="number">2005</span>;</span><br><span class="line">alert(book.edition); <span class="comment">//2</span></span><br></pre></td></tr></table></figure>
<p><code>_year</code>前面的下划线是一种常用的记号，用于表示只能通过对象方法访问的属性。</p>
<p>不一定非要同时指定getter和setter。只指定getter意味着属性是不能写，尝试写入属性会被忽略。在严格模式下，尝试写入只指定了getter函数的属性会抛出错误。类似地，只指定setter函数的属性也不能读，否则在非严格模式下会返回undefined，而在严格模式下会抛出错误。</p>
<figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="title">book.__defineGetter__("year", function()&#123;</span></span><br><span class="line">  return this._year;</span><br><span class="line">&#125;);</span><br><span class="line"><span class="title">book.__defineSetter__("year", function(newValue)&#123;</span></span><br><span class="line">  if (newValue &gt; 2004) &#123;</span><br><span class="line">    this._year = newValue;</span><br><span class="line">    this.edition += newValue - 2004;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>支持ECMAScript 5的这个方法的浏览器有IE9+（IE8只是部分实现）、Firefox 4+、Safari 5+、Opera 12+和Chrome。在这个方法之前，要创建访问器属性，一般都使用两个非标准的方法：<strong>defineGetter</strong>()和<strong>defineSetter</strong>()。<br>在不支持 Object.defineProperty() 方法的浏览器中不能修改 [[Configurable]] 和 [[Enumerable]] 。</p>
</li>
</ul>
</li>
</ol>
<h2 id="定义多个属性">定义多个属性</h2><p>由于为对象定义多个属性的可能性很大，ECMAScript 5又定义了一个Object.defineProperties()方法。利用这个方法可以通过描述符一次定义多个属性。这个方法接收两个对象参数：第一个对象是要添加和修改其属性的对象，第二个对象的属性与第一个对象中要添加或修改的属性一一对应。</p>
<figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">Object.defineProperties(book, &#123;</span><br><span class="line">  _year: &#123;</span><br><span class="line">    value: <span class="number">2004</span></span><br><span class="line">  &#125;,</span><br><span class="line">  edition: &#123;</span><br><span class="line">    value: <span class="number">1</span></span><br><span class="line">  &#125;,</span><br><span class="line">  year: &#123;</span><br><span class="line">    <span class="keyword">get</span>: <span class="function"><span class="keyword">function</span><span class="params">()</span></span>&#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">this</span>._year;</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="keyword">set</span>: <span class="function"><span class="keyword">function</span><span class="params">(newValue)</span></span>&#123;</span><br><span class="line">      <span class="keyword">if</span> (newValue &gt; <span class="number">2004</span>) &#123;</span><br><span class="line">        <span class="keyword">this</span>._year = newValue;</span><br><span class="line">        <span class="keyword">this</span>.edition += newValue - <span class="number">2004</span>;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h2 id="读取属性的特性">读取属性的特性</h2><p>使用 ECMAScript 5的 Object.getOwnPropertyDescriptor()方法，可以取得给定属性的描述符。这个方法接收两个参数：属性所在的对象和要读取其描述符的属性名称。返回值是一个对象，如果是访问器属性，这个对象的属性有configurable、enumerable、get 和set；如果是数据属性，这个对象的属性有configurable、enumerable、writable和value</p>
<figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">var descriptor = Object.getOwnPropertyDescriptor<span class="params">(book, <span class="string">"_year"</span>)</span>;</span><br><span class="line">alert<span class="params">(descriptor.value)</span>; <span class="comment">//2004</span></span><br><span class="line">alert<span class="params">(descriptor.configurable)</span>; <span class="comment">//false</span></span><br></pre></td></tr></table></figure>
<h2 id="创建对象">创建对象</h2><h3 id="工厂模式">工厂模式</h3><p>用函数来封装以特定接口创建对象的细节<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createPerson</span>(<span class="params">name, age, job</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">var</span> o = <span class="keyword">new</span> <span class="built_in">Object</span>();</span><br><span class="line">  o.name = name;</span><br><span class="line">  o.age = age;</span><br><span class="line">  o.job = job;</span><br><span class="line">  o.sayName = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    alert(<span class="keyword">this</span>.name);</span><br><span class="line">  &#125;;</span><br><span class="line">  <span class="keyword">return</span> o;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> person1 = createPerson(<span class="string">"Nicholas"</span>, <span class="number">29</span>, <span class="string">"Software Engineer"</span>);</span><br><span class="line"><span class="keyword">var</span> person2 = createPerson(<span class="string">"Greg"</span>, <span class="number">27</span>, <span class="string">"Doctor"</span>);</span><br></pre></td></tr></table></figure></p>
<p>函数createPerson()能够根据接受的参数来构建一个包含所有必要信息的Person对象。可以无数次地调用这个函数，而每次它都会返回一个包含三个属性一个方法的对象。工厂模式虽然解决了创建多个相似对象的问题，但却没有解决对象识别的问题（即怎样知道一个对象的类型）。</p>
<h3 id="构造函数模式">构造函数模式</h3><figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">function <span class="keyword">Person</span>(name, age, job)&#123;</span><br><span class="line">  this.name = name;</span><br><span class="line">  this.age = age;</span><br><span class="line">  this.job = job;</span><br><span class="line">  this.sayName = function()&#123;</span><br><span class="line">    alert(this.name);</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;</span><br><span class="line">var person1 = new <span class="keyword">Person</span>(<span class="string">"Nicholas"</span>, 29, <span class="string">"Software Engineer"</span>);</span><br><span class="line">var person2 = new <span class="keyword">Person</span>(<span class="string">"Greg"</span>, 27, <span class="string">"Doctor"</span>);</span><br></pre></td></tr></table></figure>
<p>在这个例子中，Person()函数取代了 createPerson()函数。我们注意到，Person()中的代码除了与createPerson()中相同的部分外，还存在以下不同之处：</p>
<ul>
<li>没有显式地创建对象；</li>
<li>直接将属性和方法赋给了this对象；</li>
<li>没有return语句。</li>
</ul>
<p>此外，还应该注意到函数名Person使用的是大写字母P。按照惯例，构造函数始终都应该以一个大写字母开头，而非构造函数则应该以一个小写字母开头。这个做法借鉴自其他OO语言，主要是为了区别于ECMAScript中的其他函数；本质上它和其它函数没有区别的，任何函数通过new调用就会被当做构造函数。 要创建 Person 的新实例，必须使用 new 操作符。以这种方式调用构造函数实际上会经历以下 4个步骤： (1) 创建一个新对象； (2) 将构造函数的作用域赋给新对象（因此this就指向了这个新对象）； (3) 执行构造函数中的代码（为这个新对象添加属性）； (4) 返回新对象。</p>
<ol>
<li><p>将构造函数当作函数<br> 构造函数本身就是一个普通的函数，所以我们不使用new关键字，可以看下调用Person会有什么结果</p>
 <figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">// 作为普通函数调用，由于构造函数没有返回值，所以p将是undefined</span><br><span class="line">var p = <span class="keyword">Person</span>(<span class="string">"Greg"</span>, 27, <span class="string">"Doctor"</span>); // 在全局作用域中调用一个函数时, this 对象总是指向 Global 对象，这里就是添加到 window</span><br><span class="line">window.sayName(); //<span class="string">"Greg"</span></span><br><span class="line">sayName(); //<span class="string">"Greg"</span></span><br><span class="line">// 在另一个对象的作用域中调用</span><br><span class="line">var o = new Object();</span><br><span class="line"><span class="keyword">Person</span>.call(o, <span class="string">"Kristen"</span>, 25, <span class="string">"Nurse"</span>);</span><br><span class="line">o.sayName(); //<span class="string">"Kristen"</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>构造函数的问题<br> 上面的声明函数等价于<code>this.sayName = new Function(&quot;alert(this.name)&quot;);</code></p>
<p> 使用构造函数的主要问题，就是每个方法都要在每个实例上重新创建一遍。在前面的例子中，person1和person2都有一个名为sayName()的方法，但那两个方法不是同一个Function的实例。可以通过将函数声明在全局作用域，通过<code>this.sayName = sayName</code>赋值，但在全局作用域添加函数不是一种好的做法。这个问题可以通过原型模式解决</p>
</li>
</ol>
<h3 id="原型模式">原型模式</h3><p>我们创建的每个函数都有一个 prototype（原型）属性，这个属性是一个指针，指向一个对象，而这个对象的用途是包含可以由特定类型的所有实例共享的属性和方法。如果按照字面意思来理解，那么 prototype 就是通过调用构造函数而创建的那个对象实例的原型对象。使用原型对象的好处是可以让所有对象实例共享它所包含的属性和方法。换句话说，不必在构造函数中定义对象实例的信息，而是可以将这些信息直接添加到原型对象中</p>
<figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">function <span class="keyword">Person</span>()&#123;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">Person</span>.prototype.name = <span class="string">"Nicholas"</span>;</span><br><span class="line"><span class="keyword">Person</span>.prototype.age = 29;</span><br><span class="line"><span class="keyword">Person</span>.prototype.job = <span class="string">"Software Engineer"</span>;</span><br><span class="line"><span class="keyword">Person</span>.prototype.sayName = function()&#123;</span><br><span class="line">  alert(this.name);</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<ol>
<li><p>理解原型对象<br> JavaScript中函数都是Function类型的实例，把Person当做一个指针，它指向一个Function类型的对象，每个Function实例都有prototype属性，其指向一个函数的原型对象，通过Person.prototype就可以访问到这个对象。默认情况下，每个原型对象都有一个constructor属性，这个属性指向 prototype 属性所在函数也就是Person。创建了自定义的构造函数之后，其原型对象默认只会取得constructor属性；至于其他方法，则都是从Object继承而来的。每个对象都有[[Prototype]]属性（内部属性），虽然在脚本中没有标准的方式访问[[Prototype]]，但 Firefox、Safari 和 Chrome 在每个对象上都支持一个属性<code>__proto__</code>；而在其他实现中，这个属性对脚本则是完全不可见的。这个属性指向了构造函数的原型对象，也就是Person.prototype指向的对象。JavaScript中通过递归原型链来查找对象属性，因此person1和person2可以访问到其原型Person.prototype中的属性constructor。除了通过instanceof外也可以通过person1.constructor === Person来判断是否是Person类型，但是instanceof更加可靠，因为prototype对象完全可以被覆盖，其属性constructor也就不一定是Person了。</p>
 <figure class="highlight gherkin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">+-------------------+ <span class="variable">&lt;------------------------------+</span><br><span class="line">|      Person       |                                |</span><br><span class="line">+-------------------+                                |</span><br><span class="line">|prototype|        -|--+--&gt;</span>+----------------------+  |<span class="string"></span><br><span class="line">+-------------------+  </span>|<span class="string">   </span>|<span class="string">     Person prototype </span>|<span class="string">  </span>|</span><br><span class="line">                       |<span class="string">   +----------------------+  </span>|</span><br><span class="line">+--------------------+ |<span class="string">   </span>|<span class="string">constructor</span>|<span class="string">         -</span>|<span class="string">--+</span><br><span class="line"></span>|<span class="string">      person1       </span>|<span class="string"> </span>|<span class="string">   +----------------------+</span><br><span class="line">+--------------------+ </span>|<span class="string">   </span>|<span class="string">name       </span>|<span class="string">"Nicholas"</span>|</span><br><span class="line">|<span class="string">[[Prototype]]</span>|<span class="string">     -</span>|<span class="string">-+   +----------------------+</span><br><span class="line">+--------------------+ </span>|<span class="string">   </span>|<span class="string">age        </span>|<span class="string">     29   </span>|</span><br><span class="line">                       |<span class="string">   +----------------------+</span><br><span class="line">+--------------------+ </span>|<span class="string">   </span>|<span class="string">job        </span>|<span class="string">"Soft...."</span>|</span><br><span class="line">|<span class="string">      person2       </span>|<span class="string"> </span>|<span class="string">   +----------------------+</span><br><span class="line">+--------------------+ </span>|<span class="string">   </span>|<span class="string">sayName    </span>|<span class="string">(function)</span>|</span><br><span class="line">|<span class="string">[[Prototype]]</span>|<span class="string">     -</span>|<span class="string">-+   +----------------------+</span><br><span class="line">+--------------------+</span></span><br></pre></td></tr></table></figure>
<p> 虽然在所有实现中都无法访问到[[Prototype]]，但可以通过 isPrototypeOf()方法来确定对象之间是否存在这种关系。从本质上讲，如果[[Prototype]]指向调用 isPrototypeOf()方法的对象（Person.prototype），那么这个方法就返回true</p>
<p> ECMAScript 5增加了一个新方法，叫 Object.getPrototypeOf()，在所有支持的实现中，这个方法返回[[Prototype]]的值。</p>
<p> 每当代码读取某个对象的某个属性时，都会执行一次搜索，目标是具有给定名字的属性。搜索首先从对象实例本身开始。如果在实例中找到了具有给定名字的属性，则返回该属性的值；如果没有找到，则继续搜索指针指向的原型对象，在原型对象中查找具有给定名字的属性。如果在原型对象中找到了这个属性，则返回该属性的值。</p>
<p> 虽然可以通过对象实例访问保存在原型中的值，但却不能通过对象实例重写原型中的值。如果我们在实例中添加了一个属性，而该属性与实例原型中的一个属性同名，那我们就在实例中创建该属性，该属性将会屏蔽原型中的那个属性。<code>person1.name = &quot;Greg&quot;;</code>将会覆盖原型中的name属性。</p>
<p> 不过，使用delete操作符则可以完全删除实例属性，从而让我们能够重新访问原型中的属性</p>
<p> 使用hasOwnProperty()方法可以检测一个属性是存在于实例中，还是存在于原型中。这个方法（不要忘了它是从Object继承来的）只在给定属性存在于对象实例中时，才会返回true。<code>person1.hasOwnProperty(&quot;name&quot;);person2.hasOwnProperty(&quot;name&quot;);</code>第一个返回true，第二个返回false</p>
<p> ECMAScript 5 的 Object.getOwnPropertyDescriptor() 方法只能用于实例属性,要取得原型属性的描述符,必须直接在原型对象上调用 Object.getOwnPropertyDescriptor() 方法。</p>
</li>
<li><p>原型与 in 操作符<br> 有两种方式使用in操作符：单独使用和在for-in循环中使用。在单独使用时，in操作符会在通过对象能够访问给定属性时返回true，无论该属性存在于实例中还是原型中。<code>&quot;name&quot; in person1</code>为true</p>
<p> 在使用 for-in 循环时，返回的是所有能够通过对象访问的、可枚举的（enumerated）属性，其中既包括存在于实例中的属性，也包括存在于原型中的属性。屏蔽了原型中不可枚举属性（即将[[Enumerable]]标记为 false 的属性）的实例属性也会在 for-in 循环中返回，因为根据规定，所有开发人员定义的属性都是可枚举的——只有在IE8及更早版本中例外。</p>
<p> 要取得对象上所有可枚举的实例属性，可以使用ECMAScript 5的Object.keys()方法。这个方法接收一个对象作为参数，返回一个包含所有可枚举属性的字符串数组。</p>
<p> 为减少不必要的输入，也为了从视觉上更好地封装原型的功能，更常见的做法是用一个包含所有属性和方法的对象字面量来重写整个原型对象，如下面的例子所示。</p>
 <figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">var keys = Object.keys(<span class="keyword">Person</span>.prototype); //<span class="comment">["name","age","jbo","sayName"]</span></span><br><span class="line">var keys = Object.getOwnPropertyNames(<span class="keyword">Person</span>.prototype); //<span class="comment">["constructor","name","age","jbo","sayName"]</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>更简单的原型语法<br> 如果你想要得到所有实例属性，无论它是否可枚举，都可以使用Object.getOwnPropertyNames()方法。</p>
 <figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">function <span class="keyword">Person</span>()&#123; &#125;</span><br><span class="line"><span class="keyword">Person</span>.prototype = &#123;</span><br><span class="line">    name : <span class="string">"Nicholas"</span>,</span><br><span class="line">    age : 29,</span><br><span class="line">    job: <span class="string">"Software Engineer"</span>,</span><br><span class="line">    sayName : function () &#123; alert(this.name); &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p> 这时constructor 属性不再指向 Person 了。前面曾经介绍过，每创建一个函数，就会同时创建它的 prototype 对象，这个对象也会自动获得 constructor 属性。而我们在这里使用的语法，本质上完全重写了默认的 prototype 对象，因此 constructor 属性也就变成了新对象的constructor属性（指向Object构造函数），不再指向Person函数。如果constructor的值真的很重要，可以像下面这样特意将它设置回适当的值。</p>
 <figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">function <span class="keyword">Person</span>()&#123; &#125;</span><br><span class="line"><span class="keyword">Person</span>.prototype = &#123;</span><br><span class="line">    constructor : <span class="keyword">Person</span>,</span><br><span class="line">    name : <span class="string">"Nicholas"</span>,</span><br><span class="line">    age : 29,</span><br><span class="line">    job: <span class="string">"Software Engineer"</span>,</span><br><span class="line">    sayName : function () &#123; alert(this.name); &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p> 注意，以这种方式重设 constructor 属性会导致它的[[Enumerable]]特性被设置为 true。默认情况下，原生的constructor属性是不可枚举的，因此如果你使用兼容ECMAScript 5的JavaScript引擎，可以试一试Object.defineProperty()。</p>
</li>
<li><p>原型的动态性<br> 由于在原型中查找值的过程是一次搜索,因此我们对原型对象所做的任何修改都能够立即从实例上反映出来——即使是先创建了实例后修改原型也照样如此。</p>
 <figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">var friend = new <span class="keyword">Person</span>();</span><br><span class="line"><span class="keyword">Person</span>.prototype.sayHi = function()&#123;</span><br><span class="line">  alert(<span class="string">"hi"</span>);</span><br><span class="line">&#125;;</span><br><span class="line">friend.sayHi(); //<span class="string">"hi"</span>(没有问题!)</span><br></pre></td></tr></table></figure>
<p> 其原因可以归结为实例与原型之间的松散连接关系。当我们调用person.sayHi()时，首先会在实例中搜索名为 sayHi 的属性，在没找到的情况下，会继续搜索原型。因为实例与原型之间的连接只不过是一个指针，而非一个副本，因此就可以在原型中找到新的 sayHi 属性并返回保存在那里的函数。</p>
<p> 尽管可以随时为原型添加属性和方法，并且修改能够立即在所有对象实例中反映出来，但如果是重写整个原型对象，那么情况就不一样了。我们知道，调用构造函数时会为实例添加一个指向最初原型的[[Prototype]]指针，而把原型修改为另外一个对象就等于切断了构造函数与最初原型之间的联系。请记住：实例中的指针仅指向原型，而不指向构造函数</p>
</li>
<li><p>原生对象的原型<br> 通过原生对象的原型，不仅可以取得所有默认方法的引用，而且也可以定义新方法。可以像修改自定义对象的原型一样修改原生对象的原型，因此可以随时添加方法。但是不推荐这么做。</p>
</li>
<li>原型对象的问题<br> 原型中所有属性是被很多实例共享的，这种共享对于函数非常合适。对于那些包含基本值的属性倒也说得过去，毕竟（如前面的例子所示），通过在实例上添加一个同名属性，可以隐藏原型中的对应属性。然而，对于包含引用类型值的属性来说，问题就比较突出了。</li>
</ol>
<h3 id="组合使用构造函数模式和原型模式">组合使用构造函数模式和原型模式</h3><p>构造函数模式用于定义实例属性，而原型模式用于定义方法和共享的属性。结果，每个实例都会有自己的一份实例属性的副本，但同时又共享着对方法的引用，最大限度地节省了内存。另外，这种混成模式还支持向构造函数传递参数；可谓是集两种模式之长。这是用来定义引用类型的一种默认模式。</p>
<figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">function <span class="keyword">Person</span>(name, age, job)&#123;</span><br><span class="line">  this.name = name;</span><br><span class="line">  this.age = age;</span><br><span class="line">  this.job = job;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">Person</span>.prototype = &#123;</span><br><span class="line">  constructor : <span class="keyword">Person</span>,</span><br><span class="line">  sayName : function()&#123;</span><br><span class="line">    alert(this.name);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="动态原型模式">动态原型模式</h3><p>有其他 OO 语言经验的开发人员在看到独立的构造函数和原型时,很可能会感到非常困惑。动态原型模式正是致力于解决这个问题的一个方案，它把所有信息都封装在了构造函数中，而通过在构造函数中初始化原型（仅在必要的情况下），又保持了同时使用构造函数和原型的优点。换句话说，可以通过检查某个应该存在的方法是否有效，来决定是否需要初始化原型。<br><figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">function <span class="keyword">Person</span>(name, age, job)&#123;</span><br><span class="line">  this.name = name;</span><br><span class="line">  this.age = age;</span><br><span class="line">  this.job = job;</span><br><span class="line">  //方法</span><br><span class="line">  if (typeof this.sayName != <span class="string">"function"</span>)&#123;</span><br><span class="line">    <span class="keyword">Person</span>.prototype.sayName = function()&#123;</span><br><span class="line">      alert(this.name);</span><br><span class="line">    &#125;;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>if中这段代码只会在初次调用构造函数时才会执行。</p>
<p>使用动态原型模式时,不能使用对象字面量重写原型。前面已经解释过了,如果在已经创建了实例的情况下重写原型,那么就会切断现有实例与新原型之间的联系。</p>
<h3 id="寄生构造函数模式">寄生构造函数模式</h3><figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">function <span class="keyword">Person</span>(name, age, job)&#123;</span><br><span class="line">  var o = new Object();</span><br><span class="line">  o.name = name;</span><br><span class="line">  o.age = age;</span><br><span class="line">  o.job = job;</span><br><span class="line">  o.sayName = function()&#123;</span><br><span class="line">    alert(this.name);</span><br><span class="line">  &#125;;</span><br><span class="line">  return o;</span><br><span class="line">&#125;</span><br><span class="line">var friend = new <span class="keyword">Person</span>(<span class="string">"Nicholas"</span>, 29, <span class="string">"Software Engineer"</span>);</span><br></pre></td></tr></table></figure>
<p>除了使用new操作符并把使用的包装函数叫做构造函数之外，这个模式跟工厂模式其实是一模一样的。构造函数在不返回值的情况下，默认会返回新对象实例。添加return可以重写调用构造函数时返回的值。</p>
<p>关于寄生构造函数模式，有一点需要说明：首先，返回的对象与构造函数或者与构造函数的原型属性之间没有关系；也就是说，构造函数返回的对象与在构造函数外部创建的对象没有什么不同。为此，不能依赖instanceof操作符来确定对象类型。由于存在上述问题，我们建议在可以使用其他模式的情况下，不要使用这种模式。</p>
<h3 id="稳妥构造函数模式">稳妥构造函数模式</h3><p>稳妥对象，指的是没有公共属性，而且其方法也不引用this的对象。稳妥对象最适合在一些安全的环境中（这些环境中会禁止使用this和new），或者在防止数据被其他应用程序（如Mashup程序）改动时使用。稳妥构造函数遵循与寄生构造函数类似的模式，但有两点不同：一是新创建对象的实例方法不引用this；二是不使用new 操作符调用构造函数<br><figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">function <span class="keyword">Person</span>(name, age, job)&#123;</span><br><span class="line">  var o = new Object();</span><br><span class="line">  //可以在这里定义私有变量和函数</span><br><span class="line">  o.sayName = function()&#123;</span><br><span class="line">    alert(name);</span><br><span class="line">  &#125;;</span><br><span class="line">  return o;</span><br><span class="line">&#125;</span><br><span class="line">var friend = new <span class="keyword">Person</span>(<span class="string">"Nicholas"</span>, 29, <span class="string">"Software Engineer"</span>);</span><br></pre></td></tr></table></figure></p>
<p>除了调用 sayName() 方法外,没有别的方式可以访问其数据成员。</p>
<p>与寄生构造函数模式类似，使用稳妥构造函数模式创建的对象与构造函数之间也没有什么关系，因此instanceof操作符对这种对象也没有意义。</p>
<h3 id="Class">Class</h3><p>ES6提供了更接近传统语言的写法，引入了Class（类）这个概念，作为对象的模板。通过class关键字，可以定义类。基本上，ES6的class可以看作只是一个语法糖，它的绝大部分功能，ES5都可以做到，新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。</p>
<figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">class <span class="keyword">Person</span>&#123;</span><br><span class="line">  constructor(name, age, job)&#123;</span><br><span class="line">    this.name = name;</span><br><span class="line">    this.age = age;</span><br><span class="line">    this.job = job;</span><br><span class="line">  &#125;</span><br><span class="line">  sayName()&#123;</span><br><span class="line">    alert(name);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line">var friend = new <span class="keyword">Person</span>(<span class="string">"Nicholas"</span>, 29, <span class="string">"Software Engineer"</span>);</span><br></pre></td></tr></table></figure>
<p>上面代码定义了一个“类”，可以看到里面有一个constructor方法，这就是构造方法，而this关键字则代表实例对象。注意，定义“类”的方法的时候，前面不需要加上function这个关键字，直接把函数定义放进去了就可以了。</p>
<p>如果对比前面的组合使用构造函数模式和原型模式，可以发现前面的Person构造函数对应现在Person类的构造方法constructor，前面Person原型上定义的sayName方法现在是类的内部方法。</p>
<p>ES6的类，完全可以看作构造函数的另一种写法。<br><figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">typeof <span class="keyword">Person</span> // <span class="string">"function"</span></span><br></pre></td></tr></table></figure></p>
<p>prototype对象的constructor属性，直接指向“类”的本身，这与ES5的行为是一致的。<br><figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">Person</span>.prototype.constructor === <span class="keyword">Person</span>// true</span><br></pre></td></tr></table></figure></p>
<p>另外，类的内部所有定义的方法，都是不可枚举的（enumerable）。<br><figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Object.keys(<span class="keyword">Person</span>.prototype)</span><br><span class="line">// <span class="comment">[]</span></span><br><span class="line">Object.getOwnPropertyNames(<span class="keyword">Person</span>.prototype)</span><br><span class="line">// <span class="comment">["constructor","sayName"]</span></span><br></pre></td></tr></table></figure></p>
<p>上面代码中，sayName方法是Person类内部定义的方法，它是不可枚举的。这一点与ES5的行为不一致。</p>
<h4 id="constructor方法">constructor方法</h4><p>constructor方法是类的默认方法，通过new命令生成对象实例时，自动调用该方法。一个类必须有constructor方法，如果没有显式定义，一个空的constructor方法会被默认添加。</p>
<p>constructor方法默认返回实例对象（即this），完全可以指定返回另外一个对象。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> Foo &#123;</span><br><span class="line">  <span class="constructor"><span class="keyword">constructor</span>() </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">Object</span>.create(<span class="literal">null</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">new</span> Foo() <span class="keyword">instanceof</span> Foo <span class="comment">// false</span></span><br></pre></td></tr></table></figure>
<p>上面代码中，constructor函数返回一个全新的对象，结果导致实例对象不是Foo类的实例。</p>
<h4 id="实例对象">实例对象</h4><p>生成实例对象的写法，与ES5完全一样，也是使用new命令。如果忘记加上new，像函数那样调用Class，将会报错。</p>
<p>与ES5一样，实例的属性除非显式定义在其本身（即定义在this对象上），否则都是定义在原型上（即定义在class上）。</p>
<p>与ES5一样，类的所有实例共享一个原型对象。</p>
<figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">friend.__proto__ === <span class="keyword">Person</span>.prototype  //true</span><br></pre></td></tr></table></figure>
<h4 id="name属性">name属性</h4><p>由于本质上，ES6的Class只是ES5的构造函数的一层包装，所以函数的许多特性都被Class继承，包括name属性。<br><figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">Person</span>.name</span><br></pre></td></tr></table></figure></p>
<h4 id="class_表达式">class 表达式</h4><p>与函数一样，Class也可以使用表达式的形式定义。</p>
<figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> MyClass = <span class="class"><span class="keyword">class</span> <span class="title">Me</span> </span>&#123;</span><br><span class="line">  getClassName() &#123;</span><br><span class="line">    <span class="keyword">return</span> Me.name;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>上面代码使用表达式定义了一个类。需要注意的是，这个类的名字是MyClass而不是Me，Me只在Class的内部代码可用，指代当前类。如果Class内部没用到的话，可以省略Me，也就是可以写成下面的形式。<br><figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> MyClass = <span class="class"><span class="keyword">class</span> </span>&#123; <span class="comment">/* ... */</span> &#125;;</span><br></pre></td></tr></table></figure></p>
<p>采用Class表达式，可以写出立即执行的Class。</p>
<figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">let <span class="keyword">person</span> = new class &#123;</span><br><span class="line">  constructor(name) &#123;</span><br><span class="line">    this.name = name;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  sayName() &#123;</span><br><span class="line">    console.log(this.name);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;(<span class="string">"张三"</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">person</span>.sayName(); // <span class="string">"张三"</span></span><br></pre></td></tr></table></figure>
<h4 id="不存在变量提升">不存在变量提升</h4><p>Class不存在变量提升（hoist），这一点与ES5完全不同。</p>
<figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> Foo(); <span class="comment">// ReferenceError</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Foo</span> </span>&#123;&#125;</span><br></pre></td></tr></table></figure>
<p>上面代码中，Foo类使用在前，定义在后，这样会报错，因为ES6不会把变量声明提升到代码头部。这种规定的原因与下文要提到的继承有关，必须保证子类在父类之后定义。</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  let <span class="type">Foo</span> = <span class="class"><span class="keyword">class</span> &#123;</span>&#125;;</span><br><span class="line">  <span class="class"><span class="keyword">class</span> <span class="title">Bar</span> <span class="keyword"><span class="keyword">extends</span></span> <span class="title">Foo</span> &#123;</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="严格模式">严格模式</h4><p>类和模块的内部，默认就是严格模式，所以不需要使用<code>use strict</code>指定运行模式。只要你的代码写在类或模块之中，就只有严格模式可用。</p>
<h4 id="class的取值函数（getter）和存值函数（setter）">class的取值函数（getter）和存值函数（setter）</h4><p>与ES5一样，在Class内部可以使用get和set关键字，对某个属性设置存值函数和取值函数，拦截该属性的存取行为。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> MyClass &#123;</span><br><span class="line">  <span class="constructor"><span class="keyword">constructor</span>() </span>&#123;</span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">get</span> prop() &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="string">'getter'</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">set</span> prop(value) &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'setter: '</span>+value);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> inst = <span class="keyword">new</span> MyClass();</span><br><span class="line"></span><br><span class="line">inst.prop = <span class="number">123</span>;</span><br><span class="line"><span class="comment">// setter: 123</span></span><br><span class="line"></span><br><span class="line">inst.prop</span><br><span class="line"><span class="comment">// 'getter'</span></span><br></pre></td></tr></table></figure>
<p>存值函数和取值函数是设置在属性的descriptor对象上的。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> CustomHTMLElement &#123;</span><br><span class="line">  <span class="constructor"><span class="keyword">constructor</span>(element) </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.element = element;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">get</span> html() &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>.element.innerHTML;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">set</span> html(value) &#123;</span><br><span class="line">    <span class="keyword">this</span>.element.innerHTML = value;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> descriptor = <span class="built_in">Object</span>.getOwnPropertyDescriptor(</span><br><span class="line">  CustomHTMLElement.prototype, <span class="string">"html"</span>);</span><br><span class="line"><span class="string">"get"</span> <span class="keyword">in</span> descriptor  <span class="comment">// true</span></span><br><span class="line"><span class="string">"set"</span> <span class="keyword">in</span> descriptor  <span class="comment">// true</span></span><br></pre></td></tr></table></figure>
<p>上面代码中，存值函数和取值函数是定义在html属性的描述对象上面，这与ES5完全一致。</p>
<p>下面的例子针对所有属性，设置存值函数和取值函数。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> Jedi &#123;</span><br><span class="line">  <span class="constructor"><span class="keyword">constructor</span>(options = </span>&#123;&#125;) &#123;</span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">set</span>(key, val) &#123;</span><br><span class="line">    <span class="keyword">this</span>[key] = val;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">get</span>(key) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>[key];</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面代码中，Jedi实例所有属性的存取，都会通过存值函数和取值函数。</p>
<h4 id="Class的Generator方法">Class的Generator方法</h4><p>如果某个方法之前加上星号（*），就表示该方法是一个Generator函数。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> Foo &#123;</span><br><span class="line">  <span class="constructor"><span class="keyword">constructor</span>(...args) </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.args = args;</span><br><span class="line">  &#125;</span><br><span class="line">  * [Symbol.iterator]() &#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> arg of <span class="keyword">this</span>.args) &#123;</span><br><span class="line">      <span class="keyword">yield</span> arg;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">let</span> x of <span class="keyword">new</span> Foo(<span class="string">'hello'</span>, <span class="string">'world'</span>)) &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(x);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// hello</span></span><br><span class="line"><span class="comment">// world</span></span><br></pre></td></tr></table></figure>
<p>上面代码中，Foo类的Symbol.iterator方法前有一个星号，表示该方法是一个Generator函数。Symbol.iterator方法返回一个Foo类的默认Iterator对象，for…of循环会自动调用这个方法。</p>
<h4 id="Class的静态方法">Class的静态方法</h4><p>类相当于实例的原型，所有在类中定义的方法，都会被实例继承。如果在一个方法前，加上static关键字，就表示该方法不会被实例继承，而是直接通过类来调用，这就称为“静态方法”。</p>
<figure class="highlight coffeescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Foo</span> &#123;</span></span><br><span class="line">  static classMethod() &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="string">'hello'</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">Foo.classMethod() <span class="regexp">//</span> <span class="string">'hello'</span></span><br><span class="line"></span><br><span class="line"><span class="reserved">var</span> foo = <span class="keyword">new</span> Foo();</span><br><span class="line">foo.classMethod()</span><br><span class="line"><span class="regexp">//</span> <span class="attribute">TypeError</span>: <span class="literal">undefined</span> <span class="keyword">is</span> <span class="keyword">not</span> a <span class="reserved">function</span></span><br></pre></td></tr></table></figure>
<p>上面代码中，Foo类的classMethod方法前有static关键字，表明该方法是一个静态方法，可以直接在Foo类上调用（<code>Foo.classMethod()</code>），而不是在Foo类的实例上调用。如果在实例上调用静态方法，会抛出一个错误，表示不存在该方法。</p>
<p>父类的静态方法，可以被子类继承。</p>
<p>静态方法也是可以从super对象上调用的。</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Foo</span> &#123;</span></span><br><span class="line">  static classMethod() &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="symbol">'hell</span>o';</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Bar</span> <span class="keyword"><span class="keyword">extends</span></span> <span class="title">Foo</span> &#123;</span></span><br><span class="line">  static classMethod() &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">super</span>.classMethod() + ', too';</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">Bar</span>.classMethod();</span><br></pre></td></tr></table></figure>
<h4 id="new-target属性">new.target属性</h4><p>new是从构造函数生成实例的命令。ES6为new命令引入了一个<code>new.target</code>属性，（在构造函数中）返回new命令作用于的那个构造函数。如果构造函数不是通过new命令调用的，<code>new.target</code>会返回undefined，因此这个属性可以用来确定构造函数是怎么调用的。</p>
<figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">function <span class="keyword">Person</span>(name) &#123;</span><br><span class="line">  if (new.target !== undefined) &#123;</span><br><span class="line">    this.name = name;</span><br><span class="line">  &#125; else &#123;</span><br><span class="line">    throw new Error('必须使用new生成实例');</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 另一种写法</span><br><span class="line">function <span class="keyword">Person</span>(name) &#123;</span><br><span class="line">  if (new.target === <span class="keyword">Person</span>) &#123;</span><br><span class="line">    this.name = name;</span><br><span class="line">  &#125; else &#123;</span><br><span class="line">    throw new Error('必须使用new生成实例');</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">var <span class="keyword">person</span> = new <span class="keyword">Person</span>('张三'); // 正确</span><br><span class="line">var notAPerson = <span class="keyword">Person</span>.call(<span class="keyword">person</span>, '张三');  // 报错</span><br></pre></td></tr></table></figure>
<p>上面代码确保构造函数只能通过new命令调用。</p>
<p>Class内部调用<code>new.target</code>，返回当前Class。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> Rectangle &#123;</span><br><span class="line">  <span class="constructor"><span class="keyword">constructor</span>(length, width) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="keyword">new</span>.target === Rectangle);</span><br><span class="line">    <span class="keyword">this</span>.length = length;</span><br><span class="line">    <span class="keyword">this</span>.width = width;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> obj = <span class="keyword">new</span> Rectangle(<span class="number">3</span>, <span class="number">4</span>); <span class="comment">// 输出 true</span></span><br></pre></td></tr></table></figure>
<p>需要注意的是，子类继承父类时，<code>new.target</code>会返回子类。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> Rectangle &#123;</span><br><span class="line">  <span class="constructor"><span class="keyword">constructor</span>(length, width) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="keyword">new</span>.target === Rectangle);</span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> Square extends Rectangle &#123;</span><br><span class="line">  <span class="constructor"><span class="keyword">constructor</span>(length) </span>&#123;</span><br><span class="line">    <span class="keyword">super</span>(length, length);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> obj = <span class="keyword">new</span> Square(<span class="number">3</span>); <span class="comment">// 输出 false</span></span><br></pre></td></tr></table></figure>
<p>上面代码中，<code>new.target</code>会返回子类。</p>
<p>利用这个特点，可以写出不能独立使用、必须继承后才能使用的类。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> Shape &#123;</span><br><span class="line">  <span class="constructor"><span class="keyword">constructor</span>() </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">new</span>.target === Shape) &#123;</span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">'本类不能实例化'</span>);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> Rectangle extends Shape &#123;</span><br><span class="line">  <span class="constructor"><span class="keyword">constructor</span>(length, width) </span>&#123;</span><br><span class="line">    <span class="keyword">super</span>();</span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> x = <span class="keyword">new</span> Shape();  <span class="comment">// 报错</span></span><br><span class="line"><span class="keyword">var</span> y = <span class="keyword">new</span> Rectangle(<span class="number">3</span>, <span class="number">4</span>);  <span class="comment">// 正确</span></span><br></pre></td></tr></table></figure>
<p>上面代码中，Shape类不能被实例化，只能用于继承。</p>
<p>注意，在函数外部，使用<code>new.target</code>会报错。</p>
<h4 id="Mixin模式的实现">Mixin模式的实现</h4><p>Mixin模式指的是，将多个类的接口“混入”（mix in）另一个类。它在ES6的实现如下。</p>
<figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">mix</span><span class="params">(<span class="rest_arg">...mixins</span>)</span> </span>&#123;</span><br><span class="line">  <span class="class"><span class="keyword">class</span> <span class="title">Mix</span> </span>&#123;&#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span> (let mixin of mixins) &#123;</span><br><span class="line">    copyProperties(Mix, mixin);</span><br><span class="line">    copyProperties(Mix.prototype, mixin.prototype);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> Mix;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">copyProperties</span><span class="params">(target, source)</span> </span>&#123;</span><br><span class="line">  <span class="keyword">for</span> (let key of Reflect.ownKeys(source)) &#123;</span><br><span class="line">    <span class="keyword">if</span> ( key !== <span class="string">"constructor"</span></span><br><span class="line">      &amp;&amp; key !== <span class="string">"prototype"</span></span><br><span class="line">      &amp;&amp; key !== <span class="string">"name"</span></span><br><span class="line">    ) &#123;</span><br><span class="line">      let desc = Object.getOwnPropertyDescriptor(source, key);</span><br><span class="line">      Object.defineProperty(target, key, desc);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面代码的mix函数，可以将多个对象合成为一个类。使用的时候，只要继承这个类即可。</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">DistributedEdit</span> <span class="keyword"><span class="keyword">extends</span></span> <span class="title">mix</span>(</span><span class="type">Loggable</span>, <span class="type">Serializable</span>) &#123;</span><br><span class="line">  <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="继承">继承</h2><p>ECMAScript只支持实现继承，而且其实现继承主要是依靠原型链来实现的。</p>
<h3 id="原型链">原型链</h3><p>其基本思想是利用原型让一个引用类型继承另一个引用类型的属性和方法。简单回顾一下构造函数、原型和实例的关系：每个构造函数都有一个原型对象，原型对象都包含一个指向构造函数的指针，而实例都包含一个指向原型对象的内部指针。那么，假如我们让原型对象等于另一个类型的实例，结果会怎么样呢？显然，此时的原型对象将包含一个指向另一个原型的指针，相应地，另一个原型中也包含着一个指向另一个构造函数的指针。假如另一个原型又是另一个类型的实例，那么上述关系依然成立，如此层层递进，就构成了实例与原型的链条。这就是所谓原型链的基本概念。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">SuperType</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.property = <span class="literal">true</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">SuperType.prototype.getSuperValue = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>.property;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">SubType</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.subproperty = <span class="literal">false</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//inherit from SuperType</span></span><br><span class="line">SubType.prototype = <span class="keyword">new</span> SuperType();</span><br><span class="line"></span><br><span class="line">SubType.prototype.getSubValue = <span class="function"><span class="keyword">function</span> (<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>.subproperty;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> instance = <span class="keyword">new</span> SubType();</span><br><span class="line">alert(instance.getSuperValue());   <span class="comment">//true</span></span><br><span class="line"></span><br><span class="line">alert(instance <span class="keyword">instanceof</span> <span class="built_in">Object</span>);      <span class="comment">//true</span></span><br><span class="line">alert(instance <span class="keyword">instanceof</span> SuperType);   <span class="comment">//true</span></span><br><span class="line">alert(instance <span class="keyword">instanceof</span> SubType);     <span class="comment">//true</span></span><br><span class="line">alert(<span class="built_in">Object</span>.prototype.isPrototypeOf(instance));    <span class="comment">//true</span></span><br><span class="line">alert(SuperType.prototype.isPrototypeOf(instance)); <span class="comment">//true</span></span><br><span class="line">alert(SubType.prototype.isPrototypeOf(instance));   <span class="comment">//true</span></span><br></pre></td></tr></table></figure>
<p>既然 SubType.prototype 现在是 SuperType的实例,那么 property 当然就位于该实例中了。此外,要注意 instance.constructor 现在指向的是 SuperType ,这是因为SubType 的原型指向了另一个对象—— SuperType 的原型,而这个原型对象的 constructor 属性指向的是 SuperType。<br><figure class="highlight gherkin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">+-------------------+</span><br><span class="line">|<span class="string">      SuperType    </span>|<span class="string"> &lt;--------------------------------+</span><br><span class="line">+-------------------+                                  </span>|</span><br><span class="line">|<span class="string">prototype</span>|<span class="string">        -</span>|<span class="string">----+&gt;+------------------------+  </span>|</span><br><span class="line">+-------------------+    |<span class="string"> </span>|<span class="string">   SuperType prototype  </span>|<span class="string">  </span>|</span><br><span class="line">                         |<span class="string"> +------------------------+  </span>|</span><br><span class="line">+--------------------+   |<span class="string"> </span>|<span class="string">constructor  </span>|<span class="string">         -</span>|<span class="string">--+</span><br><span class="line"></span>|<span class="string">      SubType       </span>|<span class="string">   </span>|<span class="string"> +------------------------+</span><br><span class="line">+--------------------+   </span>|<span class="string"> </span>|<span class="string">getSuperValue</span>|<span class="string">(function)</span>|</span><br><span class="line">|<span class="string">  prototype  </span>|<span class="string">     -</span>|<span class="string">-+ </span>|<span class="string"> +------------------------+</span><br><span class="line">+--------------------+ </span>|<span class="string"> +----------------------------+</span><br><span class="line">                       </span>|<span class="string">   +------------------------+ </span>|</span><br><span class="line">+--------------------+ |<span class="string">--&gt;</span>|<span class="string">    SubType prototype   </span>|<span class="string"> </span>|</span><br><span class="line">|<span class="string">      instance      </span>|<span class="string"> </span>|<span class="string">   +------------------------+ </span>|</span><br><span class="line">+--------------------+ |<span class="string">   </span>|<span class="string">[[Prototype]]</span>|<span class="string">         -</span>|<span class="string">-+</span><br><span class="line"></span>|<span class="string">[[Prototype]]</span>|<span class="string">     -</span>|<span class="string">-+   +------------------------+</span><br><span class="line">+--------------------+     </span>|<span class="string">property     </span>|<span class="string">  true    </span>|</span><br><span class="line">|<span class="string">subproperty  </span>|<span class="string"> false</span>|<span class="string">     +------------------------+</span><br><span class="line">+--------------------+     </span>|<span class="string">getSubValue  </span>|<span class="string">(function)</span>|</span><br><span class="line">                           +------------------------+</span><br></pre></td></tr></table></figure></p>
<p>通过实现原型链,本质上扩展了本章前面介绍的原型搜索机制。读者大概还记得,当以读取模式访问一个实例属性时,首先会在实例中搜索该属性。如果没有找到该属性,则会继续搜索实例的原型。在通过原型链实现继承的情况下,搜索过程就得以沿着原型链继续向上。就拿上面的例子来说,调用instance.getSuperValue() 会经历三个搜索步骤:1)搜索实例;2)搜索 SubType.prototype ; 3)搜索 SuperType.prototype ,最后一步才会找到该方法。在找不到属性或方法的情况下,搜索过程总是要一环一环地前行到原型链末端才会停下来。</p>
<ol>
<li>别忘记默认的原型<br> 事实上,前面例子中展示的原型链还少一环。我们知道,所有引用类型默认都继承了 Object ,而这个继承也是通过原型链实现的。大家要记住,所有函数的默认原型都是 Object 的实例,因此默认原型都会包含一个内部指针,指向 Object.prototype</li>
<li>确定原型和实例的关系<br> 第一种方式是使用 instanceof 操作符,只要用这个操作符来测试实例与原型链中出现过的构造函数,结果就会返回 true。<br> 第二种方式是使用 isPrototypeOf() 方法。同样,只要是原型链中出现过的原型,都可以说是该原型链所派生的实例的原型,因此 isPrototypeOf() 方法也会返回 true</li>
<li>谨慎地定义方法<br> 子类型有时候需要重写超类型中的某个方法,或者需要添加超类型中不存在的某个方法。但不管怎样,给原型添加方法的代码一定要放在替换原型的语句之后。 <figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//继承了 SuperType</span></span><br><span class="line">SubType.prototype = <span class="keyword">new</span> SuperType();</span><br><span class="line"><span class="comment">//添加新方法</span></span><br><span class="line">SubType.prototype.getSubValue = <span class="function"><span class="keyword">function</span> <span class="params">()</span></span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">this</span>.subproperty;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="comment">//重写超类型中的方法</span></span><br><span class="line">SubType.prototype.getSuperValue = <span class="function"><span class="keyword">function</span> <span class="params">()</span></span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
 还有一点需要提醒读者,即在通过原型链实现继承时,不能使用对象字面量创建原型方法。因为这样做就会重写原型链</li>
<li><p>原型链的问题<br> 原型链虽然很强大,可以用它来实现继承,但它也存在一些问题。其中,最主要的问题来自包含引用类型值的原型。</p>
<p> 在通过原型来实现继承时,原型实际上会变成另一个类型的实例。于是,原先的实例属性也就顺理成章地变成了现在的原型属性了。这些继承的属性会被子类实例共享。</p>
 <figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">SuperType</span><span class="params">()</span></span>&#123;</span><br><span class="line">  <span class="keyword">this</span>.colors = [<span class="string">"red"</span>, <span class="string">"blue"</span>, <span class="string">"green"</span>];</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">SubType</span><span class="params">()</span></span>&#123;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//继承了 SuperType</span></span><br><span class="line">SubType.prototype = <span class="keyword">new</span> SuperType();</span><br><span class="line"><span class="keyword">var</span> instance1 = <span class="keyword">new</span> SubType();</span><br><span class="line">instance1.colors.push(<span class="string">"black"</span>);</span><br><span class="line">alert(instance1.colors); <span class="comment">//"red,blue,green,black"</span></span><br><span class="line"><span class="keyword">var</span> instance2 = <span class="keyword">new</span> SubType();</span><br><span class="line">alert(instance2.colors); <span class="comment">//"red,blue,green,black"</span></span><br></pre></td></tr></table></figure>
<p> 原型链的第二个问题是:在创建子类型的实例时,不能向超类型的构造函数中传递参数。基于这两点原因实践中很少单独使用原型链</p>
</li>
</ol>
<h3 id="借用构造函数">借用构造函数</h3><p>在解决原型中包含引用类型值所带来问题的过程中,开发人员开始使用一种叫做借用构造函数(constructor stealing)的技术(有时候也叫做伪造对象或经典继承)。这种技术的基本思想相当简单,即在子类型构造函数的内部调用超类型构造函数。别忘了,函数只不过是在特定环境中执行代码的对象,因此通过使用 apply() 和 call() 方法也可以在(将来)新创建的对象上执行构造函数</p>
<figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">SuperType</span><span class="params">(name)</span></span>&#123;</span><br><span class="line">  <span class="keyword">this</span>.colors = [<span class="string">"red"</span>, <span class="string">"blue"</span>, <span class="string">"green"</span>];</span><br><span class="line">  <span class="keyword">this</span>.name = name;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">SubType</span><span class="params">()</span></span>&#123;</span><br><span class="line">  <span class="comment">//继承了 SuperType 同时还传递了参数</span></span><br><span class="line">  SuperType.call(<span class="keyword">this</span>, <span class="string">"Nicholas"</span>);</span><br><span class="line">  <span class="keyword">this</span>.age = <span class="number">29</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> instance1 = <span class="keyword">new</span> SubType();</span><br><span class="line">instance1.colors.push(<span class="string">"black"</span>);</span><br><span class="line">alert(instance1.colors); <span class="comment">//"red,blue,green,black"</span></span><br><span class="line"><span class="keyword">var</span> instance2 = <span class="keyword">new</span> SubType();</span><br><span class="line">alert(instance2.colors); <span class="comment">//"red,blue,green"</span></span><br><span class="line">alert(instance2.name);</span><br><span class="line">alert(instance2.age);</span><br></pre></td></tr></table></figure>
<ol>
<li>传递参数<br> 这种方法解决了原型链的两个主要的问题，为了确保SuperType 构造函数不会重写子类型的属性,可以在调用超类型构造函数后,再添加应该在子类型中定义的属性。</li>
<li>借用构造函数的问题<br> 如果仅仅是借用构造函数,那么也将无法避免构造函数模式存在的问题——方法都在构造函数中定义,因此函数复用就无从谈起了。而且,在超类型的原型中定义的方法,对子类型而言也是不可见的,结果所有类型都只能使用构造函数模式。考虑到这些问题,借用构造函数的技术也是很少单独使用的。</li>
</ol>
<h3 id="组合继承">组合继承</h3><p>组合继承(combination inheritance) ,有时候也叫做伪经典继承,指的是将原型链和借用构造函数的技术组合到一块,从而发挥二者之长的一种继承模式。其背后的思路是使用原型链实现对原型属性和方法的继承,而通过借用构造函数来实现对实例属性的继承。<br><figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">SuperType</span><span class="params">(name)</span>&#123;</span></span><br><span class="line">  this.name = name;</span><br><span class="line">  this.colors = [<span class="string">"red"</span>, <span class="string">"blue"</span>, <span class="string">"green"</span>];</span><br><span class="line">&#125;</span><br><span class="line">SuperType.prototype.sayName = <span class="function"><span class="keyword">function</span><span class="params">()</span>&#123;</span></span><br><span class="line">  alert<span class="params">(this.name)</span>;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">SubType</span><span class="params">(name, age)</span>&#123;</span></span><br><span class="line">  <span class="comment">//继承属性</span></span><br><span class="line">  SuperType.call<span class="params">(this, name)</span>;</span><br><span class="line">  this.age = age;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//继承方法</span></span><br><span class="line">SubType.prototype = new SuperType<span class="params">()</span>;</span><br><span class="line">SubType.prototype.constructor = SubType;</span><br><span class="line">SubType.prototype.sayAge = <span class="function"><span class="keyword">function</span><span class="params">()</span>&#123;</span></span><br><span class="line">  alert<span class="params">(this.age)</span>;</span><br><span class="line">&#125;;</span><br><span class="line">var instance1 = new SubType<span class="params">(<span class="string">"Nicholas"</span>, <span class="number">29</span>)</span>;</span><br><span class="line">instance1.colors.push<span class="params">(<span class="string">"black"</span>)</span>;</span><br><span class="line">alert<span class="params">(instance1.colors)</span>; <span class="comment">//"red,blue,green,black"</span></span><br><span class="line">instance1.sayName<span class="params">()</span>; <span class="comment">//"Nicholas";</span></span><br><span class="line">instance1.sayAge<span class="params">()</span>; <span class="comment">//29</span></span><br><span class="line">var instance2 = new SubType<span class="params">(<span class="string">"Greg"</span>, <span class="number">27</span>)</span>;</span><br><span class="line">alert<span class="params">(instance2.colors)</span>; <span class="comment">//"red,blue,green"</span></span><br><span class="line">instance2.sayName<span class="params">()</span>; <span class="comment">//"Greg";</span></span><br><span class="line">instance2.sayAge<span class="params">()</span>; <span class="comment">//27</span></span><br></pre></td></tr></table></figure></p>
<h3 id="原型式继承">原型式继承</h3><p>道格拉斯·克罗克福德在 2006 年写了一篇文章,题为 Prototypal Inheritance in JavaScript (JavaScript 中的原型式继承)。在这篇文章中,他介绍了一种实现继承的方法,这种方法并没有使用严格意义上的构造函数。他的想法是借助原型可以基于已有的对象创建新对象,同时还不必因此创建自定义类型。<br><figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">object</span><span class="params">(o)</span></span>&#123;</span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">F</span><span class="params">()</span></span>&#123;&#125;</span><br><span class="line">  F.prototype = o;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> F();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>在 object() 函数内部,先创建了一个临时性的构造函数,然后将传入的对象作为这个构造函数的原型,最后返回了这个临时类型的一个新实例。从本质上讲, object() 对传入其中的对象执行了一次浅复制。</p>
<figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">var <span class="keyword">person</span> = &#123;</span><br><span class="line">  name: <span class="string">"Nicholas"</span>,</span><br><span class="line">  friends: <span class="comment">["Shelby", "Court", "Van"]</span></span><br><span class="line">&#125;;</span><br><span class="line">//var anotherPerson = object(<span class="keyword">person</span>);</span><br><span class="line">var anotherPerson = Object.create(<span class="keyword">person</span>);</span><br><span class="line">anotherPerson.name = <span class="string">"Greg"</span>;</span><br><span class="line">anotherPerson.friends.push(<span class="string">"Rob"</span>);</span><br><span class="line">//var yetAnotherPerson = object(<span class="keyword">person</span>);</span><br><span class="line">var yetAnotherPerson = Object.create(<span class="keyword">person</span>);</span><br><span class="line">yetAnotherPerson.name = <span class="string">"Linda"</span>;</span><br><span class="line">yetAnotherPerson.friends.push(<span class="string">"Barbie"</span>);</span><br><span class="line">alert(<span class="keyword">person</span>.friends); //<span class="string">"Shelby,Court,Van,Rob,Barbie"</span></span><br></pre></td></tr></table></figure>
<p>原型式继承,要求你必须有一个对象可以作为另一个对象的基础。通过object()函数返回的对象实际上是person的副本，它们共享这引用类型属性。</p>
<p>ECMAScript 5 通过新增 Object.create() 方法规范化了原型式继承。这个方法接收两个参数:一个用作新对象原型的对象和(可选的)一个为新对象定义额外属性的对象。在传入一个参数的情况下,Object.create() 与 object() 方法的行为相同</p>
<p>Object.create() 方法的第二个参数与 Object.defineProperties() 方法的第二个参数格式相同:每个属性都是通过自己的描述符定义的。以这种方式指定的任何属性都会覆盖原型对象上的同名属性。</p>
<p>在没有必要兴师动众地创建构造函数,而只想让一个对象与另一个对象保持类似的情况下,原型式继承是完全可以胜任的。不过别忘了,包含引用类型值的属性始终都会共享相应的值,就像使用原型模式一样。</p>
<h3 id="寄生式继承">寄生式继承</h3><p>寄生式(parasitic)继承是与原型式继承紧密相关的一种思路,并且同样也是由克罗克福德推而广之的。寄生式继承的思路与寄生构造函数和工厂模式类似,即创建一个仅用于封装继承过程的函数,该函数在内部以某种方式来增强对象,最后再像真地是它做了所有工作一样返回对象。</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createAnother</span><span class="params">(original)</span></span>&#123;</span><br><span class="line">  <span class="keyword">var</span> <span class="keyword">clone</span> = object(original); <span class="comment">//通过调用函数创建一个新对象</span></span><br><span class="line">  <span class="keyword">clone</span>.sayHi = <span class="function"><span class="keyword">function</span><span class="params">()</span></span>&#123;  <span class="comment">//以某种方式来增强这个对象</span></span><br><span class="line">    alert(<span class="string">"hi"</span>);</span><br><span class="line">  &#125;;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">clone</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在主要考虑对象而不是自定义类型和构造函数的情况下,寄生式继承也是一种有用的模式。前面示范继承模式时使用的 object() 函数不是必需的;任何能够返回新对象的函数都适用于此模式。</p>
<p>使用寄生式继承来为对象添加函数,会由于不能做到函数复用而降低效率;这一点与构造函数模式类似。</p>
<h3 id="寄生组合式继承">寄生组合式继承</h3><p>组合继承是 JavaScript 最常用的继承模式;不过,它也有自己的不足。组合继承最大的问题就是无论什么情况下,都会调用两次超类型构造函数:一次是在创建子类型原型的时候,另一次是在子类型构造函数内部。没错,子类型最终会包含超类型对象的全部实例属性,但我们不得不在调用子类型构造函数时重写这些属性。</p>
<figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">SuperType</span><span class="params">(name)</span></span>&#123;</span><br><span class="line">  <span class="keyword">this</span>.name = name;</span><br><span class="line">  <span class="keyword">this</span>.colors = [<span class="string">"red"</span>, <span class="string">"blue"</span>, <span class="string">"green"</span>];</span><br><span class="line">&#125;</span><br><span class="line">SuperType.prototype.sayName = <span class="function"><span class="keyword">function</span><span class="params">()</span></span>&#123;</span><br><span class="line">  alert(<span class="keyword">this</span>.name);</span><br><span class="line">&#125;;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">SubType</span><span class="params">(name, age)</span></span>&#123;</span><br><span class="line">  SuperType.call(<span class="keyword">this</span>, name); <span class="comment">//第二次调用 SuperType()</span></span><br><span class="line">  <span class="keyword">this</span>.age = age;</span><br><span class="line">&#125;</span><br><span class="line">SubType.prototype = <span class="keyword">new</span> SuperType(); <span class="comment">//第一次调用 SuperType()</span></span><br><span class="line">SubType.prototype.constructor = SubType;</span><br><span class="line">SubType.prototype.sayAge = <span class="function"><span class="keyword">function</span><span class="params">()</span></span>&#123;</span><br><span class="line">  alert(<span class="keyword">this</span>.age);</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>在第一次调用 SuperType 构造函数时, SubType.prototype 会得到两个属性: name 和 colors ;它们都是 SuperType 的实例属性,只不过现在位于 SubType 的原型中。当调用 SubType 构造函数时,又会调用一次 SuperType 构造函数,这一次又在新对象上创建了实例属性 name 和 colors 。</p>
<p>所谓寄生组合式继承,即通过借用构造函数来继承属性,通过原型链的混成形式来继承方法。其背后的基本思路是:不必为了指定子类型的原型而调用超类型的构造函数,我们所需要的无非就是超类型原型的一个副本而已。本质上,就是使用寄生式继承来继承超类型的原型,然后再将结果指定给子类型的原型。</p>
<figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">inheritPrototype</span><span class="params">(subType, superType)</span></span>&#123;</span><br><span class="line">  <span class="keyword">var</span> prototype = object(superType.prototype); <span class="comment">//创建对象</span></span><br><span class="line">  prototype.constructor = subType; <span class="comment">//增强对象</span></span><br><span class="line">  subType.prototype = prototype; <span class="comment">//指定对象</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在函数内部,第一步是创建超类型原型的一个副本。第二步是为创建的副本添加 constructor 属性,从而弥补因重写原型而失去的默认的 constructor 属性。最后一步,将新创建的对象(即副本)赋值给子类型的原型。<br><figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">SuperType</span><span class="params">(name)</span></span>&#123;</span><br><span class="line">  <span class="keyword">this</span>.name = name;</span><br><span class="line">  <span class="keyword">this</span>.colors = [<span class="string">"red"</span>, <span class="string">"blue"</span>, <span class="string">"green"</span>];</span><br><span class="line">&#125;</span><br><span class="line">SuperType.prototype.sayName = <span class="function"><span class="keyword">function</span><span class="params">()</span></span>&#123;</span><br><span class="line">  alert(<span class="keyword">this</span>.name);</span><br><span class="line">&#125;;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">SubType</span><span class="params">(name, age)</span></span>&#123;</span><br><span class="line">  SuperType.call(<span class="keyword">this</span>, name);</span><br><span class="line">  <span class="keyword">this</span>.age = age;</span><br><span class="line">&#125;</span><br><span class="line">inheritPrototype(SubType, SuperType);</span><br><span class="line">SubType.prototype.sayAge = <span class="function"><span class="keyword">function</span><span class="params">()</span></span>&#123;</span><br><span class="line">  alert(<span class="keyword">this</span>.age);</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<p>YUI 的 YAHOO.lang.extend() 方法采用了寄生组合继承</p>
<h3 id="Class的继承">Class的继承</h3><h4 id="基本用法">基本用法</h4><p>Class之间可以通过extends关键字实现继承，这比ES5的通过修改原型链实现继承，要清晰和方便很多。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> SuperType&#123;</span><br><span class="line">  <span class="constructor"><span class="keyword">constructor</span>(name)</span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.name = name;</span><br><span class="line">  &#125;</span><br><span class="line">  sayName()&#123;</span><br><span class="line">    alert(<span class="keyword">this</span>.name);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">class</span> SubType extends SuperType&#123;</span><br><span class="line">  <span class="constructor"><span class="keyword">constructor</span>(name, age)</span>&#123;</span><br><span class="line">    <span class="keyword">super</span>(name);</span><br><span class="line">    <span class="keyword">this</span>.age = age;</span><br><span class="line">  &#125;</span><br><span class="line">  sayAge()&#123;</span><br><span class="line">    alert(<span class="keyword">this</span>.age);</span><br><span class="line">    <span class="keyword">super</span>.sayName();</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>SubType类通过extends关键字，继承了SuperType类的所有属性和方法，并且扩展了属性和方法。super关键字，它指代父类的实例（即父类的this对象）。</p>
<p>子类必须在constructor方法中调用super方法，否则新建实例时会报错。这是因为子类没有自己的this对象，而是继承父类的this对象，然后对其进行加工。如果不调用super方法，子类就得不到this对象。</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">SuperType</span> &#123;</span> <span class="comment">/* ... */</span> &#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">SubType</span> <span class="keyword"><span class="keyword">extends</span></span> <span class="title">SuperType</span> &#123;</span></span><br><span class="line">  constructor() &#123;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">let cp = <span class="keyword">new</span> <span class="type">SubType</span>(); <span class="comment">// ReferenceError</span></span><br></pre></td></tr></table></figure>
<p>对比前面的借用构造函数继承，实质是先创建子类的实例对象this，然后再将父类的属性添加到this上面（<code>Parent.apply(this)</code>）。ES6的继承机制则不同，实质是先创建父类的实例对象this（所以必须先调用super方法），然后再用子类的属性修改this。</p>
<p>如果子类没有定义constructor方法，这个方法会被默认添加，代码如下。也就是说，不管有没有显式定义，任何一个子类都有constructor方法。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="constructor"><span class="keyword">constructor</span>(...args) </span>&#123;</span><br><span class="line">  <span class="keyword">super</span>(...args);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>另一个需要注意的地方是，在子类的构造函数中，只有调用super之后，才可以使用this关键字，否则会报错。这是因为子类实例的构建，是基于对父类实例加工，只有super方法才能返回父类实例。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> SuperType&#123;</span><br><span class="line">  <span class="constructor"><span class="keyword">constructor</span>(name)</span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.name = name;</span><br><span class="line">  &#125;</span><br><span class="line">  sayName()&#123;</span><br><span class="line">    alert(<span class="keyword">this</span>.name);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">class</span> SubType extends SuperType&#123;</span><br><span class="line">  <span class="constructor"><span class="keyword">constructor</span>(name, age)</span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.age = age; <span class="comment">// ReferenceError</span></span><br><span class="line">    <span class="keyword">super</span>(name);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight coffeescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="reserved">let</span> st = <span class="keyword">new</span> SubType(<span class="string">"Howie"</span>, <span class="number">26</span>);</span><br><span class="line">st <span class="keyword">instanceof</span> SubType <span class="regexp">//</span> <span class="literal">true</span></span><br><span class="line">st <span class="keyword">instanceof</span> SuperType <span class="regexp">//</span> <span class="literal">true</span></span><br></pre></td></tr></table></figure>
<p>上面代码中，实例对象st同时是SubType和SuperType两个类的实例，这与ES5的行为完全一致。</p>
<h4 id="类的prototype属性和__proto__属性">类的prototype属性和<code>__proto__</code>属性</h4><p>大部分浏览器实现中，每一个对象都有<code>__proto__</code>属性，指向对应的构造函数的prototype属性。Class作为构造函数的语法糖，同时有prototype属性和<code>__proto__</code>属性，因此同时存在两条继承链。</p>
<ol>
<li>子类的<code>__proto__</code>属性，表示构造函数的继承，总是指向父类。</li>
<li>子类prototype属性的<code>__proto__</code>属性，表示方法的继承，总是指向父类的prototype属性。</li>
</ol>
<figure class="highlight nix"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">SubType.<span class="variable">__proto__ =</span>== SuperType // <span class="constant">true</span></span><br><span class="line">SubType.prototype.<span class="variable">__proto__ =</span>== SuperType.prototype // <span class="constant">true</span></span><br></pre></td></tr></table></figure>
<p>这样的结果是因为，类的继承是按照下面的模式实现的。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">SuperType</span> </span>&#123; &#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">SubType</span> </span>&#123; &#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// B的实例继承A的实例</span></span><br><span class="line"><span class="built_in">Object</span>.setPrototypeOf(SubType.prototype, SuperType.prototype);</span><br><span class="line"></span><br><span class="line"><span class="comment">// B继承A的静态属性</span></span><br><span class="line"><span class="built_in">Object</span>.setPrototypeOf(SubType, SuperType);</span><br><span class="line"><span class="comment">//而setPrototypeOf实现如下</span></span><br><span class="line"><span class="built_in">Object</span>.setPrototypeOf = <span class="function"><span class="keyword">function</span> (<span class="params">obj, proto</span>) </span>&#123;</span><br><span class="line">  obj.__proto__ = proto;</span><br><span class="line">  <span class="keyword">return</span> obj;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这两条继承链，可以这样理解：作为一个对象，子类的原型（<code>__proto__</code>属性）是父类；作为一个构造函数，子类的原型（prototype属性）是父类的实例。</p>
<figure class="highlight perl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">SubType.<span class="keyword">prototype</span> = new SuperType();</span><br><span class="line"><span class="regexp">//</span> 等同于</span><br><span class="line">SubType.<span class="keyword">prototype</span>.__proto_<span class="number">_</span> = SuperType.<span class="keyword">prototype</span>;</span><br></pre></td></tr></table></figure>
<h4 id="Extends_的继承目标">Extends 的继承目标</h4><p>extends关键字后面可以跟多种类型的值。</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">SubType</span> <span class="keyword"><span class="keyword">extends</span></span> <span class="title">SuperType</span>&#123;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面代码的SuperType，只要是一个有prototype属性的函数，就能被SubType继承。由于函数都有prototype属性，因此SuperType可以是任意函数。</p>
<p>下面，讨论三种特殊情况。</p>
<p>第一种特殊情况，子类继承Object类。</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">A</span> <span class="keyword"><span class="keyword">extends</span></span> <span class="title">Object</span> &#123;</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">A</span>.__proto__ === <span class="type">Object</span> <span class="comment">// true</span></span><br><span class="line"><span class="type">A</span>.prototype.__proto__ === <span class="type">Object</span>.prototype <span class="comment">// true</span></span><br></pre></td></tr></table></figure>
<p>这种情况下，A其实就是构造函数Object的复制，A的实例就是Object的实例。</p>
<p>第二种特殊情况，不存在任何继承。</p>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">A</span> </span>&#123;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">A.__proto__ === <span class="built_in">Function</span>.prototype <span class="comment">// true</span></span><br><span class="line">A.prototype.__proto__ === <span class="built_in">Object</span>.prototype <span class="comment">// true</span></span><br></pre></td></tr></table></figure>
<p>这种情况下，A作为一个基类（即不存在任何继承），就是一个普通函数，所以直接继承<code>Funciton.prototype</code>。但是，A调用后返回一个空对象（即Object实例），所以<code>A.prototype.__proto__</code>指向构造函数（Object）的prototype属性。</p>
<p>第三种特殊情况，子类继承null。</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">A</span> <span class="keyword"><span class="keyword">extends</span></span> <span class="title">null</span> &#123;</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">A</span>.__proto__ === <span class="type">Function</span>.prototype <span class="comment">// true</span></span><br><span class="line"><span class="type">A</span>.prototype.__proto__ === undefined <span class="comment">// true</span></span><br></pre></td></tr></table></figure>
<p>这种情况与第二种情况非常像。A也是一个普通函数，所以直接继承<code>Funciton.prototype</code>。但是，A调用后返回的对象不继承任何方法，所以它的<code>__proto__</code>指向<code>Function.prototype</code>，即实质上执行了下面的代码。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> A extends <span class="literal">null</span> &#123;</span><br><span class="line">  <span class="constructor"><span class="keyword">constructor</span>() </span>&#123; <span class="keyword">return</span> <span class="built_in">Object</span>.create(<span class="literal">null</span>); &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="Object-getPrototypeOf()">Object.getPrototypeOf()</h4><p>Object.getPrototypeOf方法可以用来从子类上获取父类。</p>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Object</span>.getPrototypeOf(SubType) === SuperType <span class="comment">// true</span></span><br></pre></td></tr></table></figure>
<p>因此，可以使用这个方法判断，一个类是否继承了另一个类。</p>
<h4 id="super关键字">super关键字</h4><p>上面讲过，在子类中，super关键字代表父类实例。</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">SubType</span> <span class="keyword"><span class="keyword">extends</span></span> <span class="title">SuperType</span> &#123;</span></span><br><span class="line">  get m() &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>._p * <span class="keyword">super</span>._p;</span><br><span class="line">  &#125;</span><br><span class="line">  set m() &#123;</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> <span class="type">Error</span>('该属性只读');</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面代码中，子类通过super关键字，调用父类的实例。</p>
<p>由于，对象总是继承其他对象的，所以可以在任意一个对象中，使用super关键字。</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> obj = &#123;</span><br><span class="line">  <span class="built_in">toString</span>() &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="string">"MyObject: "</span> + <span class="keyword">super</span>.<span class="built_in">toString</span>();</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">obj.<span class="built_in">toString</span>(); <span class="comment">// MyObject: [object Object]</span></span><br></pre></td></tr></table></figure>
<h4 id="实例的__proto__属性">实例的<code>__proto__</code>属性</h4><p>子类实例的<code>__proto__</code>属性的<code>__proto__</code>属性，指向父类实例的<code>__proto__</code>属性。也就是说，子类的原型的原型，是父类的原型。</p>
<figure class="highlight nix"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> <span class="variable">s1 =</span> new SuperType(<span class="string">"Howie"</span>);</span><br><span class="line"><span class="keyword">let</span> <span class="variable">s2 =</span> new SubType(<span class="string">"Howie"</span>, <span class="number">26</span>);</span><br><span class="line"></span><br><span class="line">s2.<span class="variable">__proto__ =</span>== s1.__proto // <span class="constant">false</span></span><br><span class="line">s2.__proto__.<span class="variable">__proto__ =</span>== s1.__proto__ // <span class="constant">true</span></span><br></pre></td></tr></table></figure>
<p>因此，通过子类实例的<code>__proto__.__proto__</code>属性，可以修改父类实例的行为。</p>
<h3 id="原生构造函数的继承">原生构造函数的继承</h3><p>原生构造函数是指语言内置的构造函数，通常用来生成数据结构，比如<code>Array()</code>。以前，这些原生构造函数是无法继承的，即不能自己定义一个Array的子类。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">MyArray</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="built_in">Array</span>.apply(<span class="keyword">this</span>, <span class="built_in">arguments</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">MyArray.prototype = <span class="built_in">Object</span>.create(<span class="built_in">Array</span>.prototype, &#123;</span><br><span class="line">  <span class="constructor"><span class="keyword">constructor</span>: </span>&#123;</span><br><span class="line">    value: MyArray,</span><br><span class="line">    writable: <span class="literal">true</span>,</span><br><span class="line">    configurable: <span class="literal">true</span>,</span><br><span class="line">    enumerable: <span class="literal">true</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>上面代码定义了一个继承Array的MyArray类。但是，这个类的行为与Array完全不一致。</p>
<figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> colors = <span class="keyword">new</span> MyArray();</span><br><span class="line">colors[<span class="number">0</span>] = <span class="string">"red"</span>;</span><br><span class="line">colors.length  <span class="comment">// 0</span></span><br><span class="line"></span><br><span class="line">colors.length = <span class="number">0</span>;</span><br><span class="line">colors[<span class="number">0</span>]  <span class="comment">// "red"</span></span><br></pre></td></tr></table></figure>
<p>之所以会发生这种情况，是因为原生构造函数无法外部获取，通过<code>Array.apply()</code>或者分配给原型对象都不行。ES5是先新建子类的实例对象this，再将父类的属性添加到子类上，由于父类的属性无法获取，导致无法继承原生的构造函数。</p>
<p>ES6允许继承原生构造函数定义子类，因为ES6是先新建父类的实例对象this，然后再用子类的构造函数修饰this，使得父类的所有行为都可以继承。下面是一个继承Array的例子。</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyArray</span> <span class="keyword"><span class="keyword">extends</span></span> <span class="title">Array</span> &#123;</span></span><br><span class="line">  constructor(...args) &#123;</span><br><span class="line">    <span class="keyword">super</span>(...args);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> arr = <span class="keyword">new</span> <span class="type">MyArray</span>();</span><br><span class="line">arr[<span class="number">0</span>] = <span class="number">12</span>;</span><br><span class="line">arr.length <span class="comment">// 1</span></span><br><span class="line"></span><br><span class="line">arr.length = <span class="number">0</span>;</span><br><span class="line">arr[<span class="number">0</span>] <span class="comment">// undefined</span></span><br></pre></td></tr></table></figure>
<p>上面代码定义了一个MyArray类，继承了Array构造函数，因此就可以从MyArray生成数组的实例。这意味着，ES6可以自定义原生数据结构（比如Array、String等）的子类，这是ES5无法做到的。</p>
<p>上面这个例子也说明，extends关键字不仅可以用来继承类，还可以用来继承原生的构造函数。因此可以在原生数据结构的基础上，定义自己的数据结构。下面就是定义了一个带版本功能的数组。</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">VersionedArray</span> <span class="keyword"><span class="keyword">extends</span></span> <span class="title">Array</span> &#123;</span></span><br><span class="line">  constructor() &#123;</span><br><span class="line">    <span class="keyword">super</span>();</span><br><span class="line">    <span class="keyword">this</span>.history = [[]];</span><br><span class="line">  &#125;</span><br><span class="line">  commit() &#123;</span><br><span class="line">    <span class="keyword">this</span>.history.push(<span class="keyword">this</span>.slice());</span><br><span class="line">  &#125;</span><br><span class="line">  revert() &#123;</span><br><span class="line">    <span class="keyword">this</span>.splice(<span class="number">0</span>, <span class="keyword">this</span>.length, <span class="keyword">this</span>.history[<span class="keyword">this</span>.history.length - <span class="number">1</span>]);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面代码中，VersionedArray结构会通过commit方法，将自己的上一个版本存入history属性，然后通过revert方法，可以撤销当前版本，回到上一个版本。除此之外，VersionedArray依然是一个数组，所有原生的数组方法都可以在它上面调用。</p>
<p>下面是一个自定义Error子类的例子。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> ExtendableError extends <span class="built_in">Error</span> &#123;</span><br><span class="line">  <span class="constructor"><span class="keyword">constructor</span>(message) </span>&#123;</span><br><span class="line">    <span class="keyword">super</span>();</span><br><span class="line">    <span class="keyword">this</span>.message = message;</span><br><span class="line">    <span class="keyword">this</span>.stack = (<span class="keyword">new</span> <span class="built_in">Error</span>()).stack;</span><br><span class="line">    <span class="keyword">this</span>.name = <span class="keyword">this</span>.constructor.name;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> MyError extends ExtendableError &#123;</span><br><span class="line">  <span class="constructor"><span class="keyword">constructor</span>(m) </span>&#123;</span><br><span class="line">    <span class="keyword">super</span>(m);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> myerror = <span class="keyword">new</span> MyError(<span class="string">'ll'</span>);</span><br><span class="line">myerror.message <span class="comment">// "ll"</span></span><br><span class="line">myerror <span class="keyword">instanceof</span> <span class="built_in">Error</span> <span class="comment">// true</span></span><br><span class="line">myerror.name <span class="comment">// "MyError"</span></span><br><span class="line">myerror.stack</span><br><span class="line"><span class="comment">// Error</span></span><br><span class="line"><span class="comment">//     at MyError.ExtendableError</span></span><br><span class="line"><span class="comment">//     ...</span></span><br></pre></td></tr></table></figure>
<h1 id="函数表达式">函数表达式</h1><p>之前已经讲过函数声明和函数表达式区别了。</p>
<p>Firefox、Safari、Chrome 和 Opera 都给函数定义了一个非标准的 name 属性（ES6已经正式加入name属性）,通过这个属性可以访问到给函数指定的名字。这个属性的值永远等于跟在 function 关键字后面的标识符。</p>
<p>关于函数声明,它的一个重要特征就是函数声明提升(function declaration hoisting) ,意思是在执行代码之前会先读取函数声明。这就意味着可以把函数声明放在调用它的语句后面。</p>
<figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">sayHi<span class="params">()</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">sayHi</span><span class="params">()</span>&#123;</span></span><br><span class="line">  alert<span class="params">(<span class="string">"Hi!"</span>)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>函数表达式创建的函数叫做匿名函数(anonymous function),因为 function 关键字后面没有标识符。(匿名函数有时候也叫拉姆达函数)匿名函数的 name 属性是空字符串。</p>
<p>理解函数提升的关键,就是理解函数声明与函数表达式之间的区别。例如,执行以下代码的结果可能会让人意想不到。<br><figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//不要这样做!</span></span><br><span class="line"><span class="keyword">if</span><span class="params">(condition)</span>&#123;</span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">sayHi</span><span class="params">()</span>&#123;</span></span><br><span class="line">    alert<span class="params">(<span class="string">"Hi!"</span>)</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">sayHi</span><span class="params">()</span>&#123;</span></span><br><span class="line">    alert<span class="params">(<span class="string">"Yo!"</span>)</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>实际上,这在 ECMAScript 中属于无效语法,JavaScript 引擎会尝试修正错误,将其转换为合理的状态。但问题是浏览器尝试修正错误的做法并不一致。大多数浏览器会返回第二个声明,忽略condition ;Firefox 会在 condition 为 true 时返回第一个声明。因此这种使用方式很危险,不应该出现在你的代码中。不过,如果是使用函数表达式,那就没有什么问题了。</p>
<figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//可以这样做</span></span><br><span class="line">var sayHi;</span><br><span class="line"><span class="keyword">if</span><span class="params">(condition)</span>&#123;</span><br><span class="line">  sayHi = <span class="function"><span class="keyword">function</span><span class="params">()</span>&#123;</span></span><br><span class="line">    alert<span class="params">(<span class="string">"Hi!"</span>)</span>;</span><br><span class="line">  &#125;;</span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">  sayHi = <span class="function"><span class="keyword">function</span><span class="params">()</span>&#123;</span></span><br><span class="line">    alert<span class="params">(<span class="string">"Yo!"</span>)</span>;</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="递归">递归</h2><p>之前说过可以递归时可以使用arguments.callee，但在严格模式下,不能通过脚本访问 arguments.callee ,访问这个属性会导致错误。不过,可以使用命名函数表达式来达成相同的结果。<br><figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> factorial = (function f(<span class="built_in">num</span>)&#123;</span><br><span class="line">  <span class="keyword">if</span> (<span class="built_in">num</span> &lt;= <span class="number">1</span>)&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">num</span> * f(<span class="built_in">num</span>-<span class="number">1</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure></p>
<p>以上代码创建了一个名为 f() 的命名函数表达式,然后将它赋值给变量 factorial 。即便把函数赋值给了另一个变量,函数的名字 f 仍然有效,所以递归调用照样能正确完成。这种方式在严格模式和非严格模式下都行得通</p>
<h2 id="闭包">闭包</h2><p>闭包是指有权访问另一个函数作用域中的变量的函数。创建闭包的常见方式,就是在一个函数内部创建另一个函数</p>
<figure class="highlight ceylon"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> createComparisonFunction(propertyName) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">function</span>(<span class="keyword">object</span><span class="number">1</span>, <span class="keyword">object</span><span class="number">2</span>)&#123;</span><br><span class="line">        var <span class="keyword">value</span><span class="number">1</span> = <span class="keyword">object</span><span class="number">1</span>[propertyName];</span><br><span class="line">        var <span class="keyword">value</span><span class="number">2</span> = <span class="keyword">object</span><span class="number">2</span>[propertyName];</span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">value</span><span class="number">1</span> &lt; <span class="keyword">value</span><span class="number">2</span>)&#123;</span><br><span class="line">            <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="keyword">value</span><span class="number">1</span> &gt; <span class="keyword">value</span><span class="number">2</span>)&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>即使这个内部函数被返回了,而且是在其他地方被调用了,但它仍然可以访问外部函数的变量 propertyName。之所以还能够访问这个变量,是因为内部函数的作用域链中包含createComparisonFunction() 的作用域。</p>
<p>前面讲的有关如何创建作用域链以及作用域链有什么作用的细节,对彻底理解闭包至关重要。当某个函数被调用时,会创建一个执行环境(execution context)及相应的作用域链。然后,使用 arguments 和其他命名参数的值来初始化函数的活动对象(activation object)。但在作用域链中,外部函数的活动对象始终处于第二位,外部函数的外部函数的活动对象处于第三位,……直至作为作用域链终点的全局执行环境。</p>
<figure class="highlight ceylon"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> compare(<span class="keyword">value</span><span class="number">1</span>, <span class="keyword">value</span><span class="number">2</span>)&#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">value</span><span class="number">1</span> &lt; <span class="keyword">value</span><span class="number">2</span>)&#123;</span><br><span class="line">        <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="keyword">value</span><span class="number">1</span> &gt; <span class="keyword">value</span><span class="number">2</span>)&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">var result = compare(<span class="number">5</span>, <span class="number">10</span>);</span><br></pre></td></tr></table></figure>
<p>当调用 compare() 时,会创建一个包含 arguments 、 value1 和 value2 的活动对象。全局执行环境的变量对象(包含 result和 compare )在 compare() 执行环境的作用域链中则处于第二位。</p>
<figure class="highlight gherkin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">+----------------------+</span><br><span class="line">|<span class="string">     compare          </span>|</span><br><span class="line">|<span class="string">  execution context   </span>|<span class="string">&lt;-------------------------------------------------+</span><br><span class="line">+----------------------+    +------------+      +----------------------+  </span>|</span><br><span class="line">|<span class="string">(scope chain) </span>|<span class="string">      -</span>|<span class="string">---&gt;</span>|<span class="string">scope chain </span>|<span class="string">  +--&gt;</span>|<span class="string">global variable object</span>|<span class="string">  </span>|</span><br><span class="line">+----------------------+    +------------+  |<span class="string">   +----------------------+  </span>|</span><br><span class="line">                            |<span class="string">1     </span>|<span class="string">    -</span>|<span class="string">--+   </span>|<span class="string">   compare </span>|<span class="string">         -</span>|<span class="string">--+</span><br><span class="line">                            +------------+      +----------------------+</span><br><span class="line">                            </span>|<span class="string">0     </span>|<span class="string">    -</span>|<span class="string">--+   </span>|<span class="string">   result  </span>|<span class="string"> undefined</span>|</span><br><span class="line">                            +------------+  |<span class="string">   +----------------------+</span><br><span class="line">                                            </span>|</span><br><span class="line">                                            |<span class="string">   +----------------------+</span><br><span class="line">                                            +--&gt;</span>|<span class="string">    compare()         </span>|</span><br><span class="line">                                                |<span class="string">  activation object   </span>|</span><br><span class="line">                                                +----------------------+</span><br><span class="line">                                                |<span class="string"> arguments </span>|<span class="string">  [5,10]  </span>|</span><br><span class="line">                                                +----------------------+</span><br><span class="line">                                                |<span class="string">   value1  </span>|<span class="string">  5       </span>|</span><br><span class="line">                                                +----------------------+</span><br><span class="line">                                                |<span class="string">   value2  </span>|<span class="string">  10      </span>|</span><br><span class="line">                                                +----------------------+</span><br></pre></td></tr></table></figure>
<p>后台的每个执行环境都有一个表示变量的对象——变量对象。全局环境的变量对象始终存在,而像compare() 函数这样的局部环境的变量对象,则只在函数执行的过程中存在。在创建 compare() 函数时,会创建一个预先包含全局变量对象的作用域链,这个作用域链被保存在内部的 [[Scope]] 属性中。当调用 compare() 函数时,会为函数创建一个执行环境,然后通过复制函数的 [[Scope]] 属性中的对象构建起执行环境的作用域链。此后,又有一个活动对象(在此作为变量对象使用)被创建并被推入执行环境作用域链的前端。对于这个例子中 compare() 函数的执行环境而言,其作用域链中包含两个变量对象:本地活动对象和全局变量对象。显然,作用域链本质上是一个指向变量对象的指针列表,它只引用但不实际包含变量对象。</p>
<p>无论什么时候在函数中访问一个变量时,就会从作用域链中搜索具有相应名字的变量。一般来讲,当函数执行完毕后,局部活动对象就会被销毁,内存中仅保存全局作用域(全局执行环境的变量对象)。但是,闭包的情况又有所不同。</p>
<p>在另一个函数内部定义的函数会将外部函数的活动对象添加到它的作用域链中。因此,在 createComparisonFunction() 函数内部定义的匿名函数的作用域链中,实际上将会包含外部函数 createComparisonFunction() 的活动对象。</p>
<figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">//创建函数</span><br><span class="line"><span class="keyword">var</span> compareNames = createComparisonFunction(<span class="string">"name"</span>);</span><br><span class="line">//调用函数</span><br><span class="line"><span class="keyword">var</span> <span class="literal">result</span> = compareNames(&#123; name: <span class="string">"Nicholas"</span> &#125;, &#123; name: <span class="string">"Greg"</span> &#125;);</span><br><span class="line">//解除对匿名函数的引用(以便释放内存)</span><br><span class="line">compareNames = null;</span><br></pre></td></tr></table></figure>
<p>createComparisonFunction(“name”) 返回后其活动对象并没有被销毁，因为匿名函数（即被返回的比较函数）的作用域链中有对其的引用。通过将 compareNames 设置为等于 null解除该函数的引用,就等于通知垃圾回收例程将其清除。随着匿名函数的作用域链被销毁,其他作用域(除了全局作用域)也都可以安全地销毁了。</p>
<figure class="highlight gherkin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">+----------------------+</span><br><span class="line">|<span class="string">  anonymous function  </span>|</span><br><span class="line">|<span class="string">  execution context   </span>|</span><br><span class="line">+----------------------+ +------------+</span><br><span class="line">|<span class="string">(scope chain) </span>|<span class="string">      -</span>|<span class="string">&gt;</span>|<span class="string"> scope chain</span>|</span><br><span class="line">+----------------------+ +------------+</span><br><span class="line">                         |<span class="string">2     </span>|<span class="string">    -</span>|<span class="string">--&gt;全局变量对象</span><br><span class="line">                         +------------+</span><br><span class="line">                         </span>|<span class="string">1     </span>|<span class="string">    -</span>|<span class="string">--&gt;createComparisonFunction()的活动对象</span><br><span class="line">                         +------------+</span><br><span class="line">                         </span>|<span class="string">0     </span>|<span class="string">    -</span>|<span class="string">--&gt;闭包的活动对象</span><br><span class="line">                         +------------+</span></span><br></pre></td></tr></table></figure>
<p>过度使用闭包可能会导致内存占用过多，只在绝对必要时使用闭包。</p>
<h3 id="闭包与变量">闭包与变量</h3><p>作用域链的这种配置机制引出了一个值得注意的副作用,即闭包只能取得包含函数中任何变量的最后一个值。别忘了闭包所保存的是整个变量对象,而不是某个特殊的变量。</p>
<figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">function createFunctions()&#123;</span><br><span class="line">    <span class="keyword">var</span> <span class="literal">result</span> = new <span class="type">Array</span>();</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">var</span> i=<span class="number">0</span>; i &lt; <span class="number">10</span>; i++)&#123;</span><br><span class="line">        <span class="literal">result</span>[i] = function()&#123;</span><br><span class="line">            <span class="keyword">return</span> i;</span><br><span class="line">        &#125;;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">result</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>数组中每个函数都只会返回10，而不是0到9。i在createFunctions()的活动变量中，而每个匿名函数的作用域链第二个位置就是createFunctions()的活动变量，当createFunctions()返回后，i的值为10，此时每个函数都引用着保存变量 i 的同一个变量对象,所以在每个函数内部 i 的值都是 10。通过创建另一个匿名函数强制让闭包的行为符合预期</p>
<figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">function createFunctions()&#123;</span><br><span class="line">    <span class="keyword">var</span> <span class="literal">result</span> = new <span class="type">Array</span>();</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">var</span> i=<span class="number">0</span>; i &lt; <span class="number">10</span>; i++)&#123;</span><br><span class="line">        <span class="literal">result</span>[i] = function(num)&#123;</span><br><span class="line">            <span class="keyword">return</span> function()&#123;</span><br><span class="line">                <span class="keyword">return</span> num;</span><br><span class="line">            &#125;;</span><br><span class="line">        &#125;(i);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">result</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>我们没有直接把闭包赋值给数组,而是定义了一个匿名函数,并将立即执行该匿名函数的结果赋给数组。这里的匿名函数有一个参数 num ,也就是最终的函数要返回的值。每个函数都有自己num变量的一个副本。</p>
<p>ECMASctipt6中你可以直接使用let声明i，这样i仅在for循环中有效，可以得到同样预期的结果。<br><figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">function createFunctions()&#123;</span><br><span class="line">    <span class="keyword">var</span> <span class="literal">result</span> = new <span class="type">Array</span>();</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i=<span class="number">0</span>; i &lt; <span class="number">10</span>; i++)&#123;</span><br><span class="line">        <span class="literal">result</span>[i] = function()&#123;</span><br><span class="line">            <span class="keyword">return</span> i;</span><br><span class="line">        &#125;;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">result</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h3 id="关于_this_对象">关于 this 对象</h3><p>在闭包中使用 this 对象也可能会导致一些问题。我们知道, this 对象是在运行时基于函数的执行环境绑定的:在全局函数中, this 等于 window ,而当函数被作为某个对象的方法调用时, this 等于那个对象。不过,匿名函数的执行环境具有全局性,因此其 this 对象通常指向 window。当然,在通过 call() 或 apply() 改变函数执行环境的情况下, this 就会指向其他对象。</p>
<figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> key = <span class="string">"The Window"</span>;</span><br><span class="line"><span class="keyword">var</span> object = &#123;</span><br><span class="line">    key : <span class="string">"My Object"</span>,</span><br><span class="line">    getKeyFunc : <span class="function"><span class="keyword">function</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="function"><span class="keyword">function</span><span class="params">()</span></span>&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">this</span>.key;</span><br><span class="line">        &#125;;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line">alert(object.getKeyFunc()()); <span class="comment">//"The Window"(在非严格模式下)</span></span><br></pre></td></tr></table></figure>
<p>为什么匿名函数没有取得其包含作用域(或外部作用域)的 this 对象呢? 前面曾经提到过,每个函数在被调用时都会自动取得两个特殊变量: this 和 arguments 。内部函数在搜索这两个变量时,只会搜索到其活动对象为止,因此永远不可能直接访问外部函数中的这两个变量。不过,可以把外部作用域中的 this 对象保存在一个闭包能够访问到的变量里。<br><figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> key = <span class="string">"The Window"</span>;</span><br><span class="line"><span class="keyword">var</span> object = &#123;</span><br><span class="line">    key : <span class="string">"My Object"</span>,</span><br><span class="line">    getKeyFunc : <span class="function"><span class="keyword">function</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">var</span> that = <span class="keyword">this</span>;</span><br><span class="line">        <span class="keyword">return</span> <span class="function"><span class="keyword">function</span><span class="params">()</span></span>&#123;</span><br><span class="line">            <span class="keyword">return</span> that.key;</span><br><span class="line">        &#125;;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line">alert(object.getKeyFunc()()); <span class="comment">//"The Window"(在非严格模式下)</span></span><br></pre></td></tr></table></figure></p>
<p>arguments 也存在同样的问题。如果想访问作用域中的 arguments 对象,必须将对该对象的引用保存到另一个闭包能够访问的变量中。</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> name = <span class="string">"The Window"</span>;</span><br><span class="line"><span class="keyword">var</span> <span class="class"><span class="keyword">object</span> =</span> &#123;</span><br><span class="line">    name : <span class="string">"My Object"</span>,</span><br><span class="line">    getName: function()&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.name;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="class"><span class="keyword">object</span>.<span class="title">getName</span>(</span>); <span class="comment">//"My Object"</span></span><br><span class="line">(<span class="class"><span class="keyword">object</span>.<span class="title">getName</span>)(</span>); <span class="comment">//"My Object"</span></span><br><span class="line">(<span class="class"><span class="keyword">object</span>.<span class="title">getName</span> =</span> <span class="class"><span class="keyword">object</span>.<span class="title">getName</span>)(</span>); <span class="comment">//"The Window",在非严格模式下</span></span><br></pre></td></tr></table></figure>
<h3 id="内存泄露">内存泄露</h3><p>由于 IE9 之前的版本对 JScript 对象和 COM 对象使用引用计数器来回收垃圾。而闭包中存在对外部函数的活动对象的引用，有可能导致对象不能被正常回收。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">assignHandler</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> element = <span class="built_in">document</span>.getElementById(<span class="string">"someElement"</span>);</span><br><span class="line">    element.onclick = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        alert(element.id);</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>由于匿名函数保存了一个对 assignHandler() 的活动对象的引用,因此就会导致无法减少 element 的引用数。只要匿名函数存在, element 的引用数至少也是 1,因此它所占用的内存就永远不会被回收。不过,这个问题可以通过稍微改写一下代码来解决<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">assignHandler</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> element = <span class="built_in">document</span>.getElementById(<span class="string">"someElement"</span>);</span><br><span class="line">    <span class="keyword">var</span> id = element.id;<span class="comment">//通过把 element.id 的一个副本保存在一个变量中,并且在闭包中引用该变量消除了循环引用</span></span><br><span class="line">    element.onclick = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        alert(id);</span><br><span class="line">    &#125;;</span><br><span class="line">    element = <span class="literal">null</span>;<span class="comment">//解除对 DOM 对象的引用,顺利地减少其引用数,确保正常回收其占用的内存</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="模仿块级作用域">模仿块级作用域</h2><p>如前所述,JavaScript 没有块级作用域的概念。</p>
<p>用作块级作用域(通常称为私有作用域)的匿名函数的语法如下所示。<br><figure class="highlight clojure"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="list">(<span class="keyword">function</span><span class="list">()</span><span class="collection">&#123;</span><br><span class="line">//这里是块级作用域</span><br><span class="line">&#125;</span>)</span><span class="list">()</span><span class="comment">;</span></span><br></pre></td></tr></table></figure></p>
<p>以上代码定义并立即调用了一个匿名函数。将函数声明包含在一对圆括号中,表示它实际上是一个函数表达式。而紧随其后的另一对圆括号会立即调用这个函数。</p>
<figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span><span class="params">()</span>&#123;</span></span><br><span class="line"><span class="comment">//这里是块级作用域</span></span><br><span class="line">&#125;<span class="params">()</span>; <span class="comment">//出错!</span></span><br></pre></td></tr></table></figure>
<p>这段代码会导致语法错误,是因为 JavaScript 将 function 关键字当作一个函数声明的开始,而函数声明后面不能跟圆括号。然而,函数表达式的后面可以跟圆括号。要将函数声明转换成函数表达式,只要给它加上一对圆括号即可。在下面的情况下可以不加圆括号。<br><figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> v = <span class="function"><span class="keyword">function</span><span class="params">(i)</span></span>&#123;<span class="keyword">return</span> i;&#125;(<span class="number">1</span>);</span><br></pre></td></tr></table></figure></p>
<p>这种技术经常在全局作用域中被用在函数外部,从而限制向全局作用域中添加过多的变量和函数。一般来说,我们都应该尽量少向全局作用域中添加变量和函数。在一个由很多开发人员共同参与的大型应用程序中,过多的全局变量和函数很容易导致命名冲突。而通过创建私有作用域,每个开发人员既可以使用自己的变量,又不必担心搞乱全局作用域。</p>
<p>这种做法可以减少闭包占用的内存问题,因为没有指向匿名函数的引用。只要函数执行完毕,就可以立即销毁其作用域链了。</p>
<p>ECMASctipt6中支持块级作用域，所以ES6中可以不再使用上面的执行匿名函数（IIFE）。</p>
<h2 id="私有变量">私有变量</h2><p>严格来讲,JavaScript 中没有私有成员的概念;所有对象属性都是公有的。不过,倒是有一个私有变量的概念。任何在函数中定义的变量,都可以认为是私有变量,因为不能在函数的外部访问这些变量。私有变量包括函数的参数、局部变量和在函数内部定义的其他函数。</p>
<p>我们把有权访问私有变量和私有函数的公有方法称为特权方法(privileged method)。有两种在对象上创建特权方法的方式。第一种是在构造函数中定义特权方法<br><figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">MyObject</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="comment">//私有变量和私有函数</span></span><br><span class="line">    <span class="keyword">var</span> privateVariable = <span class="number">10</span>;</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">privateFunction</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//特权方法</span></span><br><span class="line">    <span class="keyword">this</span>.publicMethod = <span class="function"><span class="keyword">function</span> <span class="params">()</span></span>&#123;</span><br><span class="line">        privateVariable++;</span><br><span class="line">        <span class="keyword">return</span> privateFunction();</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>创建 MyObject 的实例后,除了使用 publicMethod() 这一个途径外,没有任何办法可以直接访问 privateVariable 和 privateFunction() 。</p>
<p>在构造函数中定义特权方法也有一个缺点,那就是你必须使用构造函数模式来达到这个目的。</p>
<h3 id="静态私有变量">静态私有变量</h3><p>通过在私有作用域中定义私有变量或函数,同样也可以创建特权方法</p>
<figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">(<span class="function"><span class="keyword">function</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="comment">//私有变量和私有函数</span></span><br><span class="line">    <span class="keyword">var</span> privateVariable = <span class="number">10</span>;</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">privateFunction</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//构造函数</span></span><br><span class="line">    MyObject = <span class="function"><span class="keyword">function</span><span class="params">()</span></span>&#123;</span><br><span class="line">    &#125;;</span><br><span class="line">    <span class="comment">//公有/特权方法</span></span><br><span class="line">    MyObject.prototype.publicMethod = <span class="function"><span class="keyword">function</span><span class="params">()</span></span>&#123;</span><br><span class="line">        privateVariable++;</span><br><span class="line">        <span class="keyword">return</span> privateFunction();</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;)();</span><br></pre></td></tr></table></figure>
<p>注意,这个模式在定义构造函数时并没有使用函数声明,而是使用了函数表达式。函数声明只能创建局部函数,但那并不是我们想要的。出于同样的原因,我们也没有在声明 MyObject 时使用 var 关键字。但也要知道,在严格模式下给未经声明的变量赋值会导致错误。</p>
<h3 id="模块模式">模块模式</h3><p>前面的模式是用于为自定义类型创建私有变量和特权方法的。而道格拉斯所说的模块模式(module pattern)则是为单例创建私有变量和特权方法。所谓单例(singleton),指的就是只有一个实例的对象。按照惯例,JavaScript 是以对象字面量的方式来创建单例对象的。<br><figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> singleton = &#123;</span><br><span class="line">    name : value,</span><br><span class="line">    <span class="keyword">method</span> : function () &#123;</span><br><span class="line">    //这里是方法的代码</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<p>模块模式通过为单例添加私有变量和特权方法能够使其得到增强<br><figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> singleton = <span class="function"><span class="keyword">function</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="comment">//私有变量和私有函数</span></span><br><span class="line">    <span class="keyword">var</span> privateVariable = <span class="number">10</span>;</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">privateFunction</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//特权/公有方法和属性</span></span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">        publicProperty: <span class="literal">true</span>,</span><br><span class="line">        publicMethod : <span class="function"><span class="keyword">function</span><span class="params">()</span></span>&#123;</span><br><span class="line">            privateVariable++;</span><br><span class="line">            <span class="keyword">return</span> privateFunction();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;();</span><br></pre></td></tr></table></figure></p>
<h3 id="增强的模块模式">增强的模块模式</h3><p>有人进一步改进了模块模式,即在返回对象之前加入对其增强的代码。这种增强的模块模式适合那些单例必须是某种类型的实例,同时还必须添加某些属性和(或)方法对其加以增强的情况。<br><figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> singleton = <span class="function"><span class="keyword">function</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="comment">//私有变量和私有函数</span></span><br><span class="line">    <span class="keyword">var</span> privateVariable = <span class="number">10</span>;</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">privateFunction</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//创建对象</span></span><br><span class="line">    <span class="keyword">var</span> object = <span class="keyword">new</span> CustomType();</span><br><span class="line">    <span class="comment">//添加特权/公有属性和方法</span></span><br><span class="line">    object.publicProperty = <span class="literal">true</span>;</span><br><span class="line">    object.publicMethod = <span class="function"><span class="keyword">function</span><span class="params">()</span></span>&#123;</span><br><span class="line">        privateVariable++;</span><br><span class="line">        <span class="keyword">return</span> privateFunction();</span><br><span class="line">    &#125;;</span><br><span class="line">    <span class="comment">//返回这个对象</span></span><br><span class="line">    <span class="keyword">return</span> object;</span><br><span class="line">&#125;();</span><br></pre></td></tr></table></figure></p>
<h1 id="异步操作">异步操作</h1><p>异步编程对JavaScript语言很重要。JavaScript只有一个线程，如果没有异步编程，根本没法用，非卡死不可。</p>
<p>ES6诞生以前，异步编程的方法，大概有下面四种。</p>
<ul>
<li>回调函数</li>
<li>事件监听</li>
<li>发布/订阅</li>
<li>Promise 对象</li>
</ul>
<p>ES6将JavaScript异步编程带入了一个全新的阶段。</p>
<h2 id="异步基本概念">异步基本概念</h2><p>所谓”异步”，简单说就好比把一个任务分成两段，先执行第一段，然后转而执行其他任务，等做好了准备，再回过头执行第二段。</p>
<p>比如，有一个任务是读取文件进行处理，任务的第一段是向操作系统发出请求，要求读取文件。然后，程序执行其他任务，等到操作系统返回文件，再接着执行任务的第二段（处理文件）。这种不连续的执行，就叫做异步。</p>
<p>相应地，连续的执行就叫做同步。由于是连续执行，不能插入其他任务，所以操作系统从硬盘读取文件的这段时间，程序只能干等着。</p>
<h2 id="回调函数">回调函数</h2><p>JavaScript语言对异步编程的实现，就是回调函数。所谓回调函数，就是把任务的第二段单独写在一个函数里面，等到重新执行这个任务的时候，就直接调用这个函数。它的英语名字callback，直译过来就是”重新调用”。</p>
<p>读取文件进行处理，是这样写的。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">fs.readFile(<span class="string">'/etc/passwd'</span>, <span class="function"><span class="keyword">function</span> (<span class="params">err, data</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (err) <span class="keyword">throw</span> err;</span><br><span class="line">  <span class="built_in">console</span>.log(data);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>上面代码中，readFile函数的第二个参数，就是回调函数，也就是任务的第二段。等到操作系统返回了<code>/etc/passwd</code>这个文件以后，回调函数才会执行。</p>
<p>一个有趣的问题是，为什么Node.js约定，回调函数的第一个参数，必须是错误对象err（如果没有错误，该参数就是null）？原因是执行分成两段，在这两段之间抛出的错误，程序无法捕捉，只能当作参数，传入第二段。</p>
<h2 id="Promise">Promise</h2><p>回调函数本身并没有问题，它的问题出现在多个回调函数嵌套。假定读取A文件之后，再读取B文件，代码如下。</p>
<figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">fs.readFile(fileA, <span class="function"><span class="keyword">function</span> <span class="params">(err, data)</span> </span>&#123;</span><br><span class="line">  fs.readFile(fileB, <span class="function"><span class="keyword">function</span> <span class="params">(err, data)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">  &#125;);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>不难想象，如果依次读取多个文件，就会出现多重嵌套。代码不是纵向发展，而是横向发展，很快就会乱成一团，无法管理。这种情况就称为“回调函数噩梦”（callback hell）。</p>
<p>Promise就是为了解决这个问题而提出的。它不是新的语法功能，而是一种新的写法，允许将回调函数的横向加载，改成纵向加载。采用Promise，连续读取多个文件，写法如下。</p>
<figure class="highlight fortran"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">var readFile = require(<span class="string">'fs-readfile-promise'</span>);</span><br><span class="line"></span><br><span class="line">readFile(fileA)</span><br><span class="line">.<span class="keyword">then</span>(<span class="function"><span class="keyword">function</span><span class="params">(data)</span></span>&#123;</span><br><span class="line">  console.<span class="built_in">log</span>(<span class="type">data</span>.toString());</span><br><span class="line">&#125;)</span><br><span class="line">.<span class="keyword">then</span>(<span class="function"><span class="keyword">function</span><span class="params">()</span></span>&#123;</span><br><span class="line">  <span class="keyword">return</span> readFile(fileB);</span><br><span class="line">&#125;)</span><br><span class="line">.<span class="keyword">then</span>(<span class="function"><span class="keyword">function</span><span class="params">(data)</span></span>&#123;</span><br><span class="line">  console.<span class="built_in">log</span>(<span class="type">data</span>.toString());</span><br><span class="line">&#125;)</span><br><span class="line">.catch(<span class="function"><span class="keyword">function</span><span class="params">(err)</span></span> &#123;</span><br><span class="line">  console.<span class="built_in">log</span>(err);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>上面代码中，使用了fs-readfile-promise模块，它的作用就是返回一个Promise版本的readFile函数。Promise提供then方法加载回调函数，catch方法捕捉执行过程中抛出的错误。</p>
<p>可以看到，Promise 的写法只是回调函数的改进，使用then方法以后，异步任务的两段执行看得更清楚了，除此以外，并无新意。</p>
<p>Promise 的最大问题是代码冗余，原来的任务被Promise 包装了一下，不管什么操作，一眼看去都是一堆 then，原来的语义变得很不清楚。</p>
<h2 id="Generator函数">Generator函数</h2><h3 id="协程">协程</h3><p>传统的编程语言，早有异步编程的解决方案（其实是多任务的解决方案）。其中有一种叫做”协程”（coroutine），意思是多个线程互相协作，完成异步任务。</p>
<p>协程的运行流程大致如下。</p>
<ul>
<li>协程A开始执行。</li>
<li>协程A执行到一半，进入暂停，执行权转移到协程B。</li>
<li>（一段时间后）协程B交还执行权。</li>
<li>协程A恢复执行。</li>
</ul>
<p>上面流程的协程A，就是异步任务，因为它分成两段（或多段）执行。</p>
<p>举例来说，读取文件的协程写法如下。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span>* <span class="title">asnycJob</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="comment">// ...其他代码</span></span><br><span class="line">  <span class="keyword">var</span> f = <span class="keyword">yield</span> readFile(fileA);</span><br><span class="line">  <span class="comment">// ...其他代码</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面代码的函数asyncJob是一个协程，它的奥妙就在其中的yield命令。它表示执行到此处，执行权将交给其他协程。也就是说，yield命令是异步两个阶段的分界线。</p>
<p>协程遇到 yield 命令就暂停，等到执行权返回，再从暂停的地方继续往后执行。它的最大优点，就是代码的写法非常像同步操作，如果去除yield命令，简直一模一样。</p>
<h3 id="Generator函数的概念">Generator函数的概念</h3><p>Generator函数是协程在ES6的实现，最大特点就是可以交出函数的执行权（即暂停执行）。</p>
<p>整个Generator函数就是一个封装的异步任务，或者说是异步任务的容器。异步操作需要暂停的地方，都用yield语句注明。Generator函数的执行方法如下。</p>
<figure class="highlight stata"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">function* <span class="keyword">gen</span>(x)&#123;</span><br><span class="line">  <span class="keyword">var</span> y = yield x + 2;</span><br><span class="line">  <span class="keyword">return</span> y;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> <span class="keyword">g</span> = <span class="keyword">gen</span>(1);</span><br><span class="line"><span class="keyword">g</span>.next() <span class="comment">// &#123; value: 3, done: false &#125;</span></span><br><span class="line"><span class="keyword">g</span>.next() <span class="comment">// &#123; value: undefined, done: true &#125;</span></span><br></pre></td></tr></table></figure>
<p>Generator函数和普通函数最大不同就是会返回一个Iterator对象，调用该对象的next方法，会分阶段执行Generator函数，这种阶段由yield关键字划分。上例第一个next就是执行到第一个yield出现的位置。next 方法返回IteratorResult对象，含有value和done两个属性。前者是yield语句后面的值，后者表示Generator函数是否执行完毕。</p>
<h3 id="Generator函数的数据交换和错误处理">Generator函数的数据交换和错误处理</h3><p>Generator函数可以暂停执行和恢复执行，这是它能封装异步任务的根本原因。除此之外，它还有两个特性，使它可以作为异步编程的完整解决方案：函数体内外的数据交换和错误处理机制。</p>
<p>next方法返回值的value属性，是Generator函数向外输出数据；next方法还可以接受参数，这是向Generator函数体内输入数据。</p>
<figure class="highlight stata"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">function* <span class="keyword">gen</span>(x)&#123;</span><br><span class="line">  <span class="keyword">var</span> y = yield x + 2;</span><br><span class="line">  <span class="keyword">return</span> y;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> <span class="keyword">g</span> = <span class="keyword">gen</span>(1);</span><br><span class="line"><span class="keyword">g</span>.next() <span class="comment">// &#123; value: 3, done: false &#125;</span></span><br><span class="line"><span class="keyword">g</span>.next(2) <span class="comment">// &#123; value: 2, done: true &#125;</span></span><br></pre></td></tr></table></figure>
<p>上面代码中，第一个next方法的value属性，返回表达式<code>x + 2</code>的值（3）。第二个next方法带有参数2，这个参数可以传入 Generator 函数，作为上个阶段异步任务的返回结果，被函数体内的变量y接收。因此，这一步的 value 属性，返回的就是2（变量y的值）。</p>
<p>Generator 函数内部还可以部署错误处理代码，捕获函数体外抛出的错误。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span>* <span class="title">gen</span>(<span class="params">x</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">try</span> &#123;</span><br><span class="line">    <span class="keyword">var</span> y = <span class="keyword">yield</span> x + <span class="number">2</span>;</span><br><span class="line">  &#125; <span class="keyword">catch</span> (e)&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(e);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> y;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> g = gen(<span class="number">1</span>);</span><br><span class="line">g.next();</span><br><span class="line">g.throw（<span class="string">'出错了'</span>）;</span><br><span class="line"><span class="comment">// 出错了</span></span><br></pre></td></tr></table></figure>
<p>上面代码的最后一行，Generator函数体外，使用指针对象的throw方法抛出的错误，可以被函数体内的try …catch代码块捕获。这意味着，出错的代码与处理错误的代码，实现了时间和空间上的分离，这对于异步编程无疑是很重要的。</p>
<h3 id="异步任务的封装">异步任务的封装</h3><p>下面看看如何使用 Generator 函数，执行一个真实的异步任务。</p>
<figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> fetch = require('node-fetch');</span><br><span class="line"></span><br><span class="line">function* gen()&#123;</span><br><span class="line">  <span class="keyword">var</span> url = 'https://api.github.com/users/github';</span><br><span class="line">  <span class="keyword">var</span> <span class="literal">result</span> = <span class="keyword">yield</span> fetch(url);</span><br><span class="line">  console.log(<span class="literal">result</span>.bio);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面代码中，Generator函数封装了一个异步操作，该操作先读取一个远程接口，然后从JSON格式的数据解析信息。就像前面说过的，这段代码非常像同步操作，除了加上了yield命令。</p>
<p>执行这段代码的方法如下。</p>
<figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> g = gen();</span><br><span class="line"><span class="keyword">var</span> <span class="literal">result</span> = g.next();</span><br><span class="line"></span><br><span class="line"><span class="literal">result</span>.value.then(function(data)&#123;</span><br><span class="line">  <span class="keyword">return</span> data.json();</span><br><span class="line">&#125;).then(function(data)&#123;</span><br><span class="line">  g.next(data);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>上面代码中，首先执行Generator函数，获取Iterator对象，然后使用next 方法（第二行），执行异步任务的第一阶段。由于Fetch模块返回的是一个Promise对象，因此要用then方法调用下一个next 方法。</p>
<p>可以看到，虽然 Generator 函数将异步操作表示得很简洁，但是流程管理却不方便（即何时执行第一阶段、何时执行第二阶段）。</p>
<h3 id="Thunk函数">Thunk函数</h3><h4 id="参数的求值策略">参数的求值策略</h4><p>Thunk函数早在上个世纪60年代就诞生了。</p>
<p>那时，编程语言刚刚起步，计算机学家还在研究，编译器怎么写比较好。一个争论的焦点是”求值策略”，即函数的参数到底应该何时求值。</p>
<figure class="highlight stata"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> x = 1;</span><br><span class="line"></span><br><span class="line">function <span class="literal">f</span>(<span class="keyword">m</span>)&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">m</span> * 2;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="literal">f</span>(x + 5)</span><br></pre></td></tr></table></figure>
<p>上面代码先定义函数f，然后向它传入表达式<code>x + 5</code>。这个表达式应该何时求值？</p>
<p>一种意见是”传值调用”（call by value），即在进入函数体之前，就计算<code>x + 5</code>的值（等于6），再将这个值传入函数f 。C语言就采用这种策略。</p>
<p>另一种意见是”传名调用”（call by name），即直接将表达式<code>x + 5</code>传入函数体，只在用到它的时候求值。Hskell语言采用这种策略。</p>
<p>传值调用和传名调用，哪一种比较好？回答是各有利弊。传值调用比较简单，但是对参数求值的时候，实际上还没用到这个参数，有可能造成性能损失。</p>
<h4 id="Thunk函数的含义">Thunk函数的含义</h4><p>编译器的”传名调用”实现，往往是将参数放到一个临时函数之中，再将这个临时函数传入函数体。这个临时函数就叫做Thunk函数。</p>
<figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">f</span><span class="params">(m)</span></span>&#123;</span><br><span class="line">  <span class="keyword">return</span> m * <span class="number">2</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">f(x + <span class="number">5</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 等同于</span></span><br><span class="line"><span class="keyword">var</span> thunk = <span class="function"><span class="keyword">function</span> <span class="params">()</span> </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> x + <span class="number">5</span>;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">f</span><span class="params">(thunk)</span></span>&#123;</span><br><span class="line">  <span class="keyword">return</span> thunk() * <span class="number">2</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面代码中，函数f的参数<code>x + 5</code>被一个函数替换了。凡是用到原参数的地方，对<code>Thunk</code>函数求值即可。</p>
<p>这就是Thunk函数的定义，它是”传名调用”的一种实现策略，用来替换某个表达式。</p>
<h4 id="JavaScript语言的Thunk函数">JavaScript语言的Thunk函数</h4><p>JavaScript语言是传值调用，它的Thunk函数含义有所不同。在JavaScript语言中，Thunk函数替换的不是表达式，而是多参数函数，将其替换成单参数的版本，且只接受回调函数作为参数。</p>
<figure class="highlight haxe"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 正常版本的readFile（多参数版本）</span></span><br><span class="line">fs.readFile(fileName, <span class="keyword">callback</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// Thunk版本的readFile（单参数版本）</span></span><br><span class="line"><span class="keyword">var</span> readFileThunk = Thunk(fileName);</span><br><span class="line">readFileThunk(<span class="keyword">callback</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> Thunk = <span class="function"><span class="keyword">function</span> <span class="params">(fileName)</span></span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> <span class="params">(callback)</span></span>&#123;</span><br><span class="line">    <span class="keyword">return</span> fs.readFile(fileName, <span class="keyword">callback</span>);</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>上面代码中，fs模块的readFile方法是一个多参数函数，两个参数分别为文件名和回调函数。经过转换器处理，它变成了一个单参数函数，只接受回调函数作为参数。这个单参数版本，就叫做Thunk函数。</p>
<p>任何函数，只要参数有回调函数，就能写成Thunk函数的形式。下面是一个简单的Thunk函数转换器。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> Thunk = <span class="function"><span class="keyword">function</span>(<span class="params">fn</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> (<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> args = <span class="built_in">Array</span>.prototype.slice.call(<span class="built_in">arguments</span>);</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> (<span class="params">callback</span>)</span>&#123;</span><br><span class="line">      args.push(callback);</span><br><span class="line">      <span class="keyword">return</span> fn.apply(<span class="keyword">this</span>, args);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>使用上面的转换器，生成<code>fs.readFile</code>的Thunk函数。</p>
<figure class="highlight lisp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">var readFileThunk = Thunk<span class="list">(<span class="keyword">fs</span>.readFile)</span><span class="comment">;</span></span><br><span class="line">readFileThunk<span class="list">(<span class="keyword">fileA</span>)</span><span class="list">(<span class="keyword">callback</span>)</span><span class="comment">;</span></span><br></pre></td></tr></table></figure>
<h4 id="Thunkify模块">Thunkify模块</h4><p>生产环境的转换器，建议使用Thunkify模块。</p>
<p>安装。<br><figure class="highlight cmake"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ npm <span class="keyword">install</span> thunkify</span><br></pre></td></tr></table></figure></p>
<p>使用方式。<br><figure class="highlight oxygene"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> thunkify = <span class="keyword">require</span>(<span class="string">'thunkify'</span>);</span><br><span class="line"><span class="keyword">var</span> fs = <span class="keyword">require</span>(<span class="string">'fs'</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> <span class="keyword">read</span> = thunkify(fs.readFile);</span><br><span class="line"><span class="keyword">read</span>(<span class="string">'package.json'</span>)(<span class="function"><span class="keyword">function</span><span class="params">(err, str)</span><span class="comment">&#123;</span><br><span class="line">  // ...</span><br><span class="line">&#125;</span>);</span></span><br></pre></td></tr></table></figure></p>
<p>Thunkify的源码与前面那个简单的转换器非常像。主要多了一个检查机制，变量called确保回调函数只运行一次。这样的设计与下文的Generator函数相关。请看下面的例子。</p>
<figure class="highlight lasso"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">function f(a, b, callback)&#123;</span><br><span class="line">  <span class="built_in">var</span> <span class="keyword">sum</span> <span class="subst">=</span> a <span class="subst">+</span> b;</span><br><span class="line">  callback(<span class="keyword">sum</span>);</span><br><span class="line">  callback(<span class="keyword">sum</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">var</span> <span class="literal">ft</span> <span class="subst">=</span> thunkify(f);</span><br><span class="line"><span class="literal">ft</span>(<span class="number">1</span>, <span class="number">2</span>)(console<span class="built_in">.</span><span class="keyword">log</span>); <span class="comment">// 3</span></span><br></pre></td></tr></table></figure>
<p>由于thunkify只允许回调函数执行一次，所以只输出一行结果。</p>
<h4 id="Generator_函数的流程管理">Generator 函数的流程管理</h4><p>你可能会问， Thunk函数有什么用？回答是以前确实没什么用，但是ES6有了Generator函数，Thunk函数现在可以用于Generator函数的自动流程管理。</p>
<p>以读取文件为例。下面的Generator函数封装了两个异步操作。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> fs = <span class="built_in">require</span>(<span class="string">'fs'</span>);</span><br><span class="line"><span class="keyword">var</span> thunkify = <span class="built_in">require</span>(<span class="string">'thunkify'</span>);</span><br><span class="line"><span class="keyword">var</span> readFile = thunkify(fs.readFile);</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> gen = <span class="function"><span class="keyword">function</span>* (<span class="params"></span>)</span>&#123;</span><br><span class="line">  <span class="keyword">var</span> r1 = <span class="keyword">yield</span> readFile(<span class="string">'/etc/fstab'</span>);</span><br><span class="line">  <span class="built_in">console</span>.log(r1.toString());</span><br><span class="line">  <span class="keyword">var</span> r2 = <span class="keyword">yield</span> readFile(<span class="string">'/etc/shells'</span>);</span><br><span class="line">  <span class="built_in">console</span>.log(r2.toString());</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>上面代码中，yield命令用于将程序的执行权移出Generator函数，那么就需要一种方法，将执行权再交还给Generator函数。</p>
<p>这种方法就是Thunk函数，因为它可以在回调函数里，将执行权交还给Generator函数。为了便于理解，我们先看如何手动执行上面这个Generator函数。</p>
<figure class="highlight stata"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> <span class="keyword">g</span> = <span class="keyword">gen</span>();</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> r1 = <span class="keyword">g</span>.next();</span><br><span class="line">r1.value(function(<span class="keyword">err</span>, data)&#123;</span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">err</span>) throw <span class="keyword">err</span>;</span><br><span class="line">  <span class="keyword">var</span> r2 = <span class="keyword">g</span>.next(data);</span><br><span class="line">  r2.value(function(<span class="keyword">err</span>, data)&#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">err</span>) throw <span class="keyword">err</span>;</span><br><span class="line">    <span class="keyword">g</span>.next(data);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>仔细查看上面的代码，可以发现Generator函数的执行过程，其实是将同一个回调函数，反复传入next方法的value属性。这使得我们可以用递归来自动完成这个过程。</p>
<h4 id="Thunk函数的自动流程管理">Thunk函数的自动流程管理</h4><p>Thunk函数真正的威力，在于可以自动执行Generator函数。下面就是一个基于Thunk函数的Generator执行器。</p>
<figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">function run(fn) &#123;</span><br><span class="line">  <span class="keyword">var</span> gen = fn();</span><br><span class="line"></span><br><span class="line">  function next(err, data) &#123;</span><br><span class="line">    <span class="keyword">var</span> <span class="literal">result</span> = gen.next(data);</span><br><span class="line">    <span class="keyword">if</span> (<span class="literal">result</span>.done) <span class="keyword">return</span>;</span><br><span class="line">    <span class="literal">result</span>.value(next);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  next();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">run(gen);</span><br></pre></td></tr></table></figure>
<p>上面代码的run函数，就是一个Generator函数的自动执行器。内部的next函数就是Thunk的回调函数。next函数先将指针移到Generator函数的下一步（gen.next方法），然后判断Generator函数是否结束（result.done 属性），如果没结束，就将next函数再传入Thunk函数（result.value属性），否则就直接退出。前面的gen函数可以有更多读取文件操作，只要执行run函数，这些操作就会自动完成。</p>
<p>有了这个执行器，执行Generator函数方便多了。不管有多少个异步操作，直接传入run函数即可。当然，前提是每一个异步操作，都要是Thunk函数，也就是说，跟在yield命令后面的必须是Thunk函数。</p>
<p>Thunk函数并不是Generator函数自动执行的唯一方案。因为自动执行的关键是，必须有一种机制，自动控制Generator函数的流程，接收和交还程序的执行权。回调函数可以做到这一点，Promise 对象也可以做到这一点。</p>
<h3 id="co模块">co模块</h3><h4 id="基本用法-1">基本用法</h4><p><a href="https://github.com/tj/co" target="_blank" rel="external">co模块</a>是著名程序员TJ Holowaychuk于2013年6月发布的一个小工具，用于Generator函数的自动执行。</p>
<p>co模块可以让你不用编写Generator函数的执行器。</p>
<figure class="highlight lisp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">var co = require<span class="list">(<span class="quoted">'co</span>')</span><span class="comment">;</span></span><br><span class="line">co<span class="list">(<span class="keyword">gen</span>)</span><span class="comment">;</span></span><br></pre></td></tr></table></figure>
<p>上面代码中，gen函数是前面定义的，Generator函数只要传入co函数，就会自动执行。</p>
<p>co函数返回一个Promise对象，因此可以用then方法添加回调函数。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">co(gen).then(<span class="function"><span class="keyword">function</span> (<span class="params"></span>)</span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'Generator 函数执行完成'</span>);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>上面代码中，等到Generator函数执行结束，就会输出一行提示。</p>
<h4 id="co模块的原理">co模块的原理</h4><p>为什么co可以自动执行Generator函数？</p>
<p>前面说过，Generator就是一个异步操作的容器。它的自动执行需要一种机制，当异步操作有了结果，能够自动交回执行权。</p>
<p>两种方法可以做到这一点。</p>
<ol>
<li>回调函数。将异步操作包装成Thunk函数，在回调函数里面交回执行权。</li>
<li>Promise 对象。将异步操作包装成Promise对象，用then方法交回执行权。</li>
</ol>
<p>co模块其实就是将两种自动执行器（Thunk函数和Promise对象），包装成一个模块。使用co的前提条件是，Generator函数的yield命令后面，只能是Thunk函数或Promise对象。</p>
<p>已经介绍了基于Thunk函数的自动执行器。下面来看，基于Promise对象的自动执行器。这是理解co模块必须的。</p>
<h4 id="基于Promise对象的自动执行">基于Promise对象的自动执行</h4><p>还是沿用上面的例子。首先，把fs模块的readFile方法包装成一个Promise对象。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> fs = <span class="built_in">require</span>(<span class="string">'fs'</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> readFile = <span class="function"><span class="keyword">function</span> (<span class="params">fileName</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span> (<span class="params">resolve, reject</span>)</span>&#123;</span><br><span class="line">    fs.readFile(fileName, <span class="function"><span class="keyword">function</span>(<span class="params">error, data</span>)</span>&#123;</span><br><span class="line">      <span class="keyword">if</span> (error) reject(error);</span><br><span class="line">      resolve(data);</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> gen = <span class="function"><span class="keyword">function</span>* (<span class="params"></span>)</span>&#123;</span><br><span class="line">  <span class="keyword">var</span> f1 = <span class="keyword">yield</span> readFile(<span class="string">'/etc/fstab'</span>);</span><br><span class="line">  <span class="keyword">var</span> f2 = <span class="keyword">yield</span> readFile(<span class="string">'/etc/shells'</span>);</span><br><span class="line">  <span class="built_in">console</span>.log(f1.toString());</span><br><span class="line">  <span class="built_in">console</span>.log(f2.toString());</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>然后，手动执行上面的Generator函数。</p>
<figure class="highlight fortran"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">var g = gen();</span><br><span class="line"></span><br><span class="line">g.next().<span class="keyword">value</span>.<span class="keyword">then</span>(<span class="function"><span class="keyword">function</span><span class="params">(data)</span></span>&#123;</span><br><span class="line">  g.next(<span class="type">data</span>).<span class="keyword">value</span>.<span class="keyword">then</span>(<span class="function"><span class="keyword">function</span><span class="params">(data)</span></span>&#123;</span><br><span class="line">    g.next(<span class="type">data</span>);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>手动执行其实就是用then方法，层层添加回调函数。理解了这一点，就可以写出一个自动执行器。</p>
<figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">function run(gen)&#123;</span><br><span class="line">  <span class="keyword">var</span> g = gen();</span><br><span class="line"></span><br><span class="line">  function next(data)&#123;</span><br><span class="line">    <span class="keyword">var</span> <span class="literal">result</span> = g.next(data);</span><br><span class="line">    <span class="keyword">if</span> (<span class="literal">result</span>.done) <span class="keyword">return</span> <span class="literal">result</span>.value;</span><br><span class="line">    <span class="literal">result</span>.value.then(function(data)&#123;</span><br><span class="line">      next(data);</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  next();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">run(gen);</span><br></pre></td></tr></table></figure>
<p>上面代码中，只要Generator函数还没执行到最后一步，next函数就调用自身，以此实现自动执行。</p>
<p>co就是上面那个自动执行器的扩展，它的源码只有几十行，非常简单。增加了一些类型检查的操作。</p>
<h4 id="处理并发的异步操作">处理并发的异步操作</h4><p>co支持并发的异步操作，即允许某些操作同时进行，等到它们全部完成，才进行下一步。</p>
<p>这时，要把并发的操作都放在数组或对象里面，跟在yield语句后面。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 数组的写法</span></span><br><span class="line">co(<span class="function"><span class="keyword">function</span>* (<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> res = <span class="keyword">yield</span> [</span><br><span class="line">    <span class="built_in">Promise</span>.resolve(<span class="number">1</span>),</span><br><span class="line">    <span class="built_in">Promise</span>.resolve(<span class="number">2</span>)</span><br><span class="line">  ];</span><br><span class="line">  <span class="built_in">console</span>.log(res);</span><br><span class="line">&#125;).catch(onerror);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 对象的写法</span></span><br><span class="line">co(<span class="function"><span class="keyword">function</span>* (<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> res = <span class="keyword">yield</span> &#123;</span><br><span class="line">    <span class="number">1</span>: <span class="built_in">Promise</span>.resolve(<span class="number">1</span>),</span><br><span class="line">    <span class="number">2</span>: <span class="built_in">Promise</span>.resolve(<span class="number">2</span>),</span><br><span class="line">  &#125;;</span><br><span class="line">  <span class="built_in">console</span>.log(res);</span><br><span class="line">&#125;).catch(onerror);</span><br></pre></td></tr></table></figure>
<p>下面是另一个例子。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">co(<span class="function"><span class="keyword">function</span>* (<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> values = [n1, n2, n3];</span><br><span class="line">  <span class="keyword">yield</span> values.map(somethingAsync);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span>* <span class="title">somethingAsync</span>(<span class="params">x</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// do something async</span></span><br><span class="line">  <span class="keyword">return</span> y</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面的代码允许并发三个somethingAsync异步操作，等到它们全部完成，才会进行下一步。</p>
<h2 id="async函数">async函数</h2><h3 id="含义">含义</h3><p>async 函数是什么？一句话，async函数就是Generator函数的语法糖。</p>
<p>前文有一个Generator函数，依次读取两个文件。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> fs = <span class="built_in">require</span>(<span class="string">'fs'</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> readFile = <span class="function"><span class="keyword">function</span> (<span class="params">fileName</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span> (<span class="params">resolve, reject</span>)</span>&#123;</span><br><span class="line">    fs.readFile(fileName, <span class="function"><span class="keyword">function</span>(<span class="params">error, data</span>)</span>&#123;</span><br><span class="line">      <span class="keyword">if</span> (error) reject(error);</span><br><span class="line">      resolve(data);</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> gen = <span class="function"><span class="keyword">function</span>* (<span class="params"></span>)</span>&#123;</span><br><span class="line">  <span class="keyword">var</span> f1 = <span class="keyword">yield</span> readFile(<span class="string">'/etc/fstab'</span>);</span><br><span class="line">  <span class="keyword">var</span> f2 = <span class="keyword">yield</span> readFile(<span class="string">'/etc/shells'</span>);</span><br><span class="line">  <span class="built_in">console</span>.log(f1.toString());</span><br><span class="line">  <span class="built_in">console</span>.log(f2.toString());</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>写成 async 函数，就是下面这样。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> asyncReadFile = <span class="keyword">async</span> <span class="function"><span class="keyword">function</span> (<span class="params"></span>)</span>&#123;</span><br><span class="line">  <span class="keyword">var</span> f1 = <span class="keyword">await</span> readFile(<span class="string">'/etc/fstab'</span>);</span><br><span class="line">  <span class="keyword">var</span> f2 = <span class="keyword">await</span> readFile(<span class="string">'/etc/shells'</span>);</span><br><span class="line">  <span class="built_in">console</span>.log(f1.toString());</span><br><span class="line">  <span class="built_in">console</span>.log(f2.toString());</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>一比较就会发现，async函数就是将Generator函数的星号（*）替换成async，将yield替换成await，仅此而已。</p>
<p>async 函数对 Generator 函数的改进，体现在以下三点。</p>
<ol>
<li>内置执行器。Generator函数的执行必须靠执行器，所以才有了co模块，而async 函数自带执行器。也就是说，async函数的执行，与普通函数一模一样，只要一行。 <code>var result = asyncReadFile();</code></li>
<li>更好的语义。async和await，比起星号和yield，语义更清楚了。async表示函数里有异步操作，await 表示紧跟在后面的表达式需要等待结果。</li>
<li>更广的适用性。 co模块约定，yield命令后面只能是Thunk函数或Promise对象，而async函数的await命令后面，可以跟Promise对象和原始类型的值（数值、字符串和布尔值，但这时等同于同步操作）。</li>
</ol>
<h3 id="async函数的实现">async函数的实现</h3><p>async 函数的实现，就是将 Generator 函数和自动执行器，包装在一个函数里。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">fn</span>(<span class="params">args</span>)</span>&#123;</span><br><span class="line">  <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 等同于</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">fn</span>(<span class="params">args</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">return</span> spawn(<span class="function"><span class="keyword">function</span>*(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>所有的 async 函数都可以写成上面的第二种形式，其中的 spawn 函数就是自动执行器。</p>
<p>下面给出 spawn 函数的实现，基本就是前文自动执行器的翻版。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">spawn</span>(<span class="params">genF</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span>(<span class="params">resolve, reject</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> gen = genF();</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">step</span>(<span class="params">nextF</span>) </span>&#123;</span><br><span class="line">      <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">var</span> next = nextF();</span><br><span class="line">      &#125; <span class="keyword">catch</span>(e) &#123;</span><br><span class="line">        <span class="keyword">return</span> reject(e);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">if</span>(next.done) &#123;</span><br><span class="line">        <span class="keyword">return</span> resolve(next.value);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="built_in">Promise</span>.resolve(next.value).then(<span class="function"><span class="keyword">function</span>(<span class="params">v</span>) </span>&#123;</span><br><span class="line">        step(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123; <span class="keyword">return</span> gen.next(v); &#125;);</span><br><span class="line">      &#125;, <span class="function"><span class="keyword">function</span>(<span class="params">e</span>) </span>&#123;</span><br><span class="line">        step(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123; <span class="keyword">return</span> gen.throw(e); &#125;);</span><br><span class="line">      &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">    step(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123; <span class="keyword">return</span> gen.next(<span class="literal">undefined</span>); &#125;);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>async 函数是非常新的语法功能，新到都不属于 ES6，而是属于 ES7。目前，它仍处于提案阶段，但是转码器 Babel 和 regenerator 都已经支持，转码后就能使用。</p>
<h3 id="async_函数的用法">async 函数的用法</h3><p>同Generator函数一样，async函数返回一个Promise对象，可以使用then方法添加回调函数。当函数执行的时候，一旦遇到 await 就会先返回，等到触发的异步操作完成，再接着执行函数体内后面的语句。</p>
<p>下面是一个例子。</p>
<figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">async function getStockPriceByName(name) &#123;</span><br><span class="line">  <span class="keyword">var</span> symbol = await getStockSymbol(name);</span><br><span class="line">  <span class="keyword">var</span> stockPrice = await getStockPrice(symbol);</span><br><span class="line">  <span class="keyword">return</span> stockPrice;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">getStockPriceByName('goog').then(function (<span class="literal">result</span>)&#123;</span><br><span class="line">  console.log(<span class="literal">result</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>上面代码是一个获取股票报价的函数，函数前面的async关键字，表明该函数内部有异步操作。调用该函数时，会立即返回一个Promise对象。</p>
<p>下面的例子，指定多少毫秒后输出一个值。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">timeout</span>(<span class="params">ms</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>((resolve, reject) =&gt; &#123;</span><br><span class="line">    setTimeout(resolve, ms);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">asyncPrint</span>(<span class="params">value, ms</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">await</span> timeout(ms);</span><br><span class="line">  <span class="built_in">console</span>.log(value)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">asyncPrint(<span class="string">'hello world'</span>, <span class="number">50</span>);</span><br></pre></td></tr></table></figure>
<h3 id="注意点">注意点</h3><p>await命令后面的Promise对象，运行结果可能是rejected，所以最好把await命令放在try…catch代码块中。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">myFunction</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">try</span> &#123;</span><br><span class="line">    <span class="keyword">await</span> somethingThatReturnsAPromise();</span><br><span class="line">  &#125; <span class="keyword">catch</span> (err) &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(err);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 另一种写法</span></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">myFunction</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">await</span> somethingThatReturnsAPromise().catch(<span class="function"><span class="keyword">function</span> (<span class="params">err</span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(err);</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>await命令只能用在async函数之中，如果用在普通函数，就会报错。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">dbFuc</span>(<span class="params">db</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> docs = [&#123;&#125;, &#123;&#125;, &#123;&#125;];</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 报错</span></span><br><span class="line">  docs.forEach(<span class="function"><span class="keyword">function</span> (<span class="params">doc</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">await</span> db.post(doc);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">dbFuc</span>(<span class="params">db</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> docs = [&#123;&#125;, &#123;&#125;, &#123;&#125;];</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 可能得到错误结果</span></span><br><span class="line">  docs.forEach(<span class="keyword">async</span> <span class="function"><span class="keyword">function</span> (<span class="params">doc</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">await</span> db.post(doc);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面代码可能不会正常工作，原因是这时三个<code>db.post</code>操作将是并发执行，也就是同时执行，而不是继发执行。正确的写法是采用for循环。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">dbFuc</span>(<span class="params">db</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> docs = [&#123;&#125;, &#123;&#125;, &#123;&#125;];</span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> doc <span class="keyword">of</span> docs) &#123;</span><br><span class="line">    <span class="keyword">await</span> db.post(doc);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>如果确实希望多个请求并发执行，可以使用 Promise.all 方法。</p>
<figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">async <span class="function"><span class="keyword">function</span> <span class="title">dbFuc</span><span class="params">(db)</span> &#123;</span></span><br><span class="line">  <span class="built_in">let</span> docs = [&#123;&#125;, &#123;&#125;, &#123;&#125;];</span><br><span class="line">  <span class="built_in">let</span> promises = docs.map<span class="params">(<span class="params">(doc)</span> =&gt; db.post<span class="params">(doc)</span>)</span>;</span><br><span class="line"></span><br><span class="line">  <span class="built_in">let</span> results = await Promise.all<span class="params">(promises)</span>;</span><br><span class="line">  console.<span class="built_in">log</span><span class="params">(results)</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 或者使用下面的写法</span></span><br><span class="line"></span><br><span class="line">async <span class="function"><span class="keyword">function</span> <span class="title">dbFuc</span><span class="params">(db)</span> &#123;</span></span><br><span class="line">  <span class="built_in">let</span> docs = [&#123;&#125;, &#123;&#125;, &#123;&#125;];</span><br><span class="line">  <span class="built_in">let</span> promises = docs.map<span class="params">(<span class="params">(doc)</span> =&gt; db.post<span class="params">(doc)</span>)</span>;</span><br><span class="line"></span><br><span class="line">  <span class="built_in">let</span> results = [];</span><br><span class="line">  <span class="keyword">for</span> <span class="params">(let promise of promises)</span> &#123;</span><br><span class="line">    results.push<span class="params">(await promise)</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  console.<span class="built_in">log</span><span class="params">(results)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>ES6将await增加为保留字。使用这个词作为标识符，在ES5是合法的，在ES6将抛出SyntaxError。</p>
<h3 id="与Promise、Generator的比较">与Promise、Generator的比较</h3><p>我们通过一个例子，来看Async函数与Promise、Generator函数的区别。</p>
<p>假定某个DOM元素上面，部署了一系列的动画，前一个动画结束，才能开始后一个。如果当中有一个动画出错，就不再往下执行，返回上一个成功执行的动画的返回值。</p>
<p>首先是Promise的写法。</p>
<figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">chainAnimationsPromise</span><span class="params">(elem, animations)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 变量ret用来保存上一个动画的返回值</span></span><br><span class="line">  <span class="keyword">var</span> ret = <span class="literal">null</span>;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 新建一个空的Promise</span></span><br><span class="line">  <span class="keyword">var</span> p = Promise.resolve();</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 使用then方法，添加所有动画</span></span><br><span class="line">  <span class="keyword">for</span>(<span class="keyword">var</span> anim <span class="keyword">in</span> animations) &#123;</span><br><span class="line">    p = p.then(<span class="function"><span class="keyword">function</span><span class="params">(val)</span> </span>&#123;</span><br><span class="line">      ret = val;</span><br><span class="line">      <span class="keyword">return</span> anim(elem);</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 返回一个部署了错误捕捉机制的Promise</span></span><br><span class="line">  <span class="keyword">return</span> p.<span class="keyword">catch</span>(<span class="function"><span class="keyword">function</span><span class="params">(e)</span> </span>&#123;</span><br><span class="line">    <span class="comment">/* 忽略错误，继续执行 */</span></span><br><span class="line">  &#125;).then(<span class="function"><span class="keyword">function</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> ret;</span><br><span class="line">  &#125;);</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>虽然Promise的写法比回调函数的写法大大改进，但是一眼看上去，代码完全都是Promise的API（then、catch等等），操作本身的语义反而不容易看出来。</p>
<p>接着是Generator函数的写法。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">chainAnimationsGenerator</span>(<span class="params">elem, animations</span>) </span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> spawn(<span class="function"><span class="keyword">function</span>*(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> ret = <span class="literal">null</span>;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">      <span class="keyword">for</span>(<span class="keyword">var</span> anim <span class="keyword">of</span> animations) &#123;</span><br><span class="line">        ret = <span class="keyword">yield</span> anim(elem);</span><br><span class="line">      &#125;</span><br><span class="line">    &#125; <span class="keyword">catch</span>(e) &#123;</span><br><span class="line">      <span class="comment">/* 忽略错误，继续执行 */</span></span><br><span class="line">    &#125;</span><br><span class="line">      <span class="keyword">return</span> ret;</span><br><span class="line">  &#125;);</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面代码使用Generator函数遍历了每个动画，语义比Promise写法更清晰，用户定义的操作全部都出现在spawn函数的内部。这个写法的问题在于，必须有一个任务运行器，自动执行Generator函数，上面代码的spawn函数就是自动执行器，它返回一个Promise对象，而且必须保证yield语句后面的表达式，必须返回一个Promise。</p>
<p>最后是Async函数的写法。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">chainAnimationsAsync</span>(<span class="params">elem, animations</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> ret = <span class="literal">null</span>;</span><br><span class="line">  <span class="keyword">try</span> &#123;</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">var</span> anim <span class="keyword">of</span> animations) &#123;</span><br><span class="line">      ret = <span class="keyword">await</span> anim(elem);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125; <span class="keyword">catch</span>(e) &#123;</span><br><span class="line">    <span class="comment">/* 忽略错误，继续执行 */</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> ret;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>可以看到Async函数的实现最简洁，最符合语义，几乎没有语义不相关的代码。它将Generator写法中的自动执行器，改在语言层面提供，不暴露给用户，因此代码量最少。如果使用Generator写法，自动执行器需要用户自己提供。</p>

      
    </div>
    <footer class="article-footer">
	  
	  <!-- 百度分享 Start -->
	  <div class="bdsharebuttonbox"><a href="#" class="bds_more" data-cmd="more"></a><a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间"></a><a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a><a href="#" class="bds_tqq" data-cmd="tqq" title="分享到腾讯微博"></a><a href="#" class="bds_renren" data-cmd="renren" title="分享到人人网"></a><a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信"></a></div>
	  <!-- 百度分享 End -->
	  
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/JavaScript/">JavaScript</a></li></ul>

	  
<span>
Updated:<time datetime="2015-09-01T03:35:47.000Z" itemprop="dateModified">2015-09-01</time>
</span>


    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2015/09/01/javascript-summary/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          JavaScript 总结
        
      </div>
    </a>
  
  
    <a href="/2015/08/28/javascript-reference-type/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">JavaScript 引用类型</div>
    </a>
  
</nav>

  
</article>



<!-- 多说评论框 start -->

<section id="comments">
  <div class="ds-thread"  data-thread-key="/2015/08/28/javascript-oop-function-expression-and-async/" data-title="JavaScript 面向对象程序设计、函数表达式和异步编程" data-url="http://howiefh.github.io/2015/08/28/javascript-oop-function-expression-and-async/" id="ds_thread">
    <noscript>Please enable JavaScript to view the <a href="//duoshuo.com/?ref_noscript">comments powered by duoshuo.</a></noscript>
  </div>
</section>

<!-- 多说评论框 end -->
</section>
        
          
  <div id="toc" class="toc-aside">
  <h2 class="toc-title">Contents</h2>
    
        <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#面向对象程序设计"><span class="toc-number">1.</span> <span class="toc-text">面向对象程序设计</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#属性类型"><span class="toc-number">1.1.</span> <span class="toc-text">属性类型</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#定义多个属性"><span class="toc-number">1.2.</span> <span class="toc-text">定义多个属性</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#读取属性的特性"><span class="toc-number">1.3.</span> <span class="toc-text">读取属性的特性</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#创建对象"><span class="toc-number">1.4.</span> <span class="toc-text">创建对象</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#工厂模式"><span class="toc-number">1.4.1.</span> <span class="toc-text">工厂模式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#构造函数模式"><span class="toc-number">1.4.2.</span> <span class="toc-text">构造函数模式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#原型模式"><span class="toc-number">1.4.3.</span> <span class="toc-text">原型模式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#组合使用构造函数模式和原型模式"><span class="toc-number">1.4.4.</span> <span class="toc-text">组合使用构造函数模式和原型模式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#动态原型模式"><span class="toc-number">1.4.5.</span> <span class="toc-text">动态原型模式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#寄生构造函数模式"><span class="toc-number">1.4.6.</span> <span class="toc-text">寄生构造函数模式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#稳妥构造函数模式"><span class="toc-number">1.4.7.</span> <span class="toc-text">稳妥构造函数模式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Class"><span class="toc-number">1.4.8.</span> <span class="toc-text">Class</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#constructor方法"><span class="toc-number">1.4.8.1.</span> <span class="toc-text">constructor方法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#实例对象"><span class="toc-number">1.4.8.2.</span> <span class="toc-text">实例对象</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#name属性"><span class="toc-number">1.4.8.3.</span> <span class="toc-text">name属性</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#class_表达式"><span class="toc-number">1.4.8.4.</span> <span class="toc-text">class 表达式</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#不存在变量提升"><span class="toc-number">1.4.8.5.</span> <span class="toc-text">不存在变量提升</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#严格模式"><span class="toc-number">1.4.8.6.</span> <span class="toc-text">严格模式</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#class的取值函数（getter）和存值函数（setter）"><span class="toc-number">1.4.8.7.</span> <span class="toc-text">class的取值函数（getter）和存值函数（setter）</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Class的Generator方法"><span class="toc-number">1.4.8.8.</span> <span class="toc-text">Class的Generator方法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Class的静态方法"><span class="toc-number">1.4.8.9.</span> <span class="toc-text">Class的静态方法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#new-target属性"><span class="toc-number">1.4.8.10.</span> <span class="toc-text">new.target属性</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Mixin模式的实现"><span class="toc-number">1.4.8.11.</span> <span class="toc-text">Mixin模式的实现</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#继承"><span class="toc-number">1.5.</span> <span class="toc-text">继承</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#原型链"><span class="toc-number">1.5.1.</span> <span class="toc-text">原型链</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#借用构造函数"><span class="toc-number">1.5.2.</span> <span class="toc-text">借用构造函数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#组合继承"><span class="toc-number">1.5.3.</span> <span class="toc-text">组合继承</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#原型式继承"><span class="toc-number">1.5.4.</span> <span class="toc-text">原型式继承</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#寄生式继承"><span class="toc-number">1.5.5.</span> <span class="toc-text">寄生式继承</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#寄生组合式继承"><span class="toc-number">1.5.6.</span> <span class="toc-text">寄生组合式继承</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Class的继承"><span class="toc-number">1.5.7.</span> <span class="toc-text">Class的继承</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#基本用法"><span class="toc-number">1.5.7.1.</span> <span class="toc-text">基本用法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#类的prototype属性和__proto__属性"><span class="toc-number">1.5.7.2.</span> <span class="toc-text">类的prototype属性和__proto__属性</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Extends_的继承目标"><span class="toc-number">1.5.7.3.</span> <span class="toc-text">Extends 的继承目标</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Object-getPrototypeOf()"><span class="toc-number">1.5.7.4.</span> <span class="toc-text">Object.getPrototypeOf()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#super关键字"><span class="toc-number">1.5.7.5.</span> <span class="toc-text">super关键字</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#实例的__proto__属性"><span class="toc-number">1.5.7.6.</span> <span class="toc-text">实例的__proto__属性</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#原生构造函数的继承"><span class="toc-number">1.5.8.</span> <span class="toc-text">原生构造函数的继承</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#函数表达式"><span class="toc-number">2.</span> <span class="toc-text">函数表达式</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#递归"><span class="toc-number">2.1.</span> <span class="toc-text">递归</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#闭包"><span class="toc-number">2.2.</span> <span class="toc-text">闭包</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#闭包与变量"><span class="toc-number">2.2.1.</span> <span class="toc-text">闭包与变量</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#关于_this_对象"><span class="toc-number">2.2.2.</span> <span class="toc-text">关于 this 对象</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#内存泄露"><span class="toc-number">2.2.3.</span> <span class="toc-text">内存泄露</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#模仿块级作用域"><span class="toc-number">2.3.</span> <span class="toc-text">模仿块级作用域</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#私有变量"><span class="toc-number">2.4.</span> <span class="toc-text">私有变量</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#静态私有变量"><span class="toc-number">2.4.1.</span> <span class="toc-text">静态私有变量</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#模块模式"><span class="toc-number">2.4.2.</span> <span class="toc-text">模块模式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#增强的模块模式"><span class="toc-number">2.4.3.</span> <span class="toc-text">增强的模块模式</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#异步操作"><span class="toc-number">3.</span> <span class="toc-text">异步操作</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#异步基本概念"><span class="toc-number">3.1.</span> <span class="toc-text">异步基本概念</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#回调函数"><span class="toc-number">3.2.</span> <span class="toc-text">回调函数</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Promise"><span class="toc-number">3.3.</span> <span class="toc-text">Promise</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Generator函数"><span class="toc-number">3.4.</span> <span class="toc-text">Generator函数</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#协程"><span class="toc-number">3.4.1.</span> <span class="toc-text">协程</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Generator函数的概念"><span class="toc-number">3.4.2.</span> <span class="toc-text">Generator函数的概念</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Generator函数的数据交换和错误处理"><span class="toc-number">3.4.3.</span> <span class="toc-text">Generator函数的数据交换和错误处理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#异步任务的封装"><span class="toc-number">3.4.4.</span> <span class="toc-text">异步任务的封装</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Thunk函数"><span class="toc-number">3.4.5.</span> <span class="toc-text">Thunk函数</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#参数的求值策略"><span class="toc-number">3.4.5.1.</span> <span class="toc-text">参数的求值策略</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Thunk函数的含义"><span class="toc-number">3.4.5.2.</span> <span class="toc-text">Thunk函数的含义</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#JavaScript语言的Thunk函数"><span class="toc-number">3.4.5.3.</span> <span class="toc-text">JavaScript语言的Thunk函数</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Thunkify模块"><span class="toc-number">3.4.5.4.</span> <span class="toc-text">Thunkify模块</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Generator_函数的流程管理"><span class="toc-number">3.4.5.5.</span> <span class="toc-text">Generator 函数的流程管理</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Thunk函数的自动流程管理"><span class="toc-number">3.4.5.6.</span> <span class="toc-text">Thunk函数的自动流程管理</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#co模块"><span class="toc-number">3.4.6.</span> <span class="toc-text">co模块</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#基本用法-1"><span class="toc-number">3.4.6.1.</span> <span class="toc-text">基本用法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#co模块的原理"><span class="toc-number">3.4.6.2.</span> <span class="toc-text">co模块的原理</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#基于Promise对象的自动执行"><span class="toc-number">3.4.6.3.</span> <span class="toc-text">基于Promise对象的自动执行</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#处理并发的异步操作"><span class="toc-number">3.4.6.4.</span> <span class="toc-text">处理并发的异步操作</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#async函数"><span class="toc-number">3.5.</span> <span class="toc-text">async函数</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#含义"><span class="toc-number">3.5.1.</span> <span class="toc-text">含义</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#async函数的实现"><span class="toc-number">3.5.2.</span> <span class="toc-text">async函数的实现</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#async_函数的用法"><span class="toc-number">3.5.3.</span> <span class="toc-text">async 函数的用法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#注意点"><span class="toc-number">3.5.4.</span> <span class="toc-text">注意点</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#与Promise、Generator的比较"><span class="toc-number">3.5.5.</span> <span class="toc-text">与Promise、Generator的比较</span></a></li></ol></li></ol></li></ol>
    
  </div>

<aside id="sidebar">

  
    
<div class="widget-wrap">
  <h3 class="widget-title">ABOUT ME</h3>
  <ul class="widget about-me">
    
    <li><img class="author" title="About me" src="http://fh-1.qiniudn.com/okal-eltocat.jpg" /></li>
    
    
    <li>Hi,I'm FengHao.</li>
    
    <li>I'll share something interesting and my learning experience with you at this blog.</li>
    
    <li>前博客:<a href="http://hi.baidu.com/idea_star" target="_BLANK">百度空间</a></li>
    
  </ul>
</div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Categories</h3>
    <div class="widget">
      <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/Android/">Android</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/C/">C</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Database/">Database</a><span class="category-list-count">13</span><ul class="category-list-child"><li class="category-list-item"><a class="category-list-link" href="/categories/Database/MongoDB/">MongoDB</a><span class="category-list-count">10</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Database/MySQL/">MySQL</a><span class="category-list-count">2</span></li></ul></li><li class="category-list-item"><a class="category-list-link" href="/categories/Eclipse/">Eclipse</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/FTP/">FTP</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Git/">Git</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Hexo/">Hexo</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Java/">Java</a><span class="category-list-count">20</span><ul class="category-list-child"><li class="category-list-item"><a class="category-list-link" href="/categories/Java/FreeMarker/">FreeMarker</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Java/Shiro/">Shiro</a><span class="category-list-count">2</span></li></ul></li><li class="category-list-item"><a class="category-list-link" href="/categories/JavaEE/">JavaEE</a><span class="category-list-count">4</span><ul class="category-list-child"><li class="category-list-item"><a class="category-list-link" href="/categories/JavaEE/Hibernate/">Hibernate</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/JavaEE/JSP/">JSP</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/JavaEE/Spring/">Spring</a><span class="category-list-count">2</span></li></ul></li><li class="category-list-item"><a class="category-list-link" href="/categories/JavaScript/">JavaScript</a><span class="category-list-count">5</span><ul class="category-list-child"><li class="category-list-item"><a class="category-list-link" href="/categories/JavaScript/jQuery/">jQuery</a><span class="category-list-count">1</span></li></ul></li><li class="category-list-item"><a class="category-list-link" href="/categories/Linux/">Linux</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/PHP/">PHP</a><span class="category-list-count">5</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Suse/">Suse</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Ubuntu/">Ubuntu</a><span class="category-list-count">5</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Vim/">Vim</a><span class="category-list-count">8</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/编程/">编程</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/软件/">软件</a><span class="category-list-count">1</span></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tag Cloud</h3>
    <div class="widget tagcloud">
      <a href="/tags/Android/" style="font-size: 14.75px; color: #65bfa7">Android</a> <a href="/tags/C/" style="font-size: 13.88px; color: #71c1c2">C</a> <a href="/tags/CAS/" style="font-size: 13px; color: #7dc3de">CAS</a> <a href="/tags/Chrome/" style="font-size: 13px; color: #7dc3de">Chrome</a> <a href="/tags/Clean-Code/" style="font-size: 13.88px; color: #71c1c2">Clean Code</a> <a href="/tags/Database/" style="font-size: 13px; color: #7dc3de">Database</a> <a href="/tags/Eclipse/" style="font-size: 13px; color: #7dc3de">Eclipse</a> <a href="/tags/FTP/" style="font-size: 13.88px; color: #71c1c2">FTP</a> <a href="/tags/FreeMarker/" style="font-size: 14.75px; color: #65bfa7">FreeMarker</a> <a href="/tags/Gcc/" style="font-size: 13px; color: #7dc3de">Gcc</a> <a href="/tags/Git/" style="font-size: 14.75px; color: #65bfa7">Git</a> <a href="/tags/Github-Pages/" style="font-size: 13px; color: #7dc3de">Github Pages</a> <a href="/tags/Hexo/" style="font-size: 14.75px; color: #65bfa7">Hexo</a> <a href="/tags/Hibernate/" style="font-size: 13px; color: #7dc3de">Hibernate</a> <a href="/tags/JSP/" style="font-size: 13px; color: #7dc3de">JSP</a> <a href="/tags/JVM/" style="font-size: 14.75px; color: #65bfa7">JVM</a> <a href="/tags/Java/" style="font-size: 14.75px; color: #65bfa7">Java</a> <a href="/tags/JavaMail/" style="font-size: 13px; color: #7dc3de">JavaMail</a> <a href="/tags/JavaScript/" style="font-size: 16.5px; color: #4dbc6f">JavaScript</a> <a href="/tags/Linux/" style="font-size: 13.88px; color: #71c1c2">Linux</a> <a href="/tags/Log/" style="font-size: 13px; color: #7dc3de">Log</a> <a href="/tags/Markdown/" style="font-size: 13.88px; color: #71c1c2">Markdown</a> <a href="/tags/MongoDB/" style="font-size: 20px; color: #1db400">MongoDB</a> <a href="/tags/MySQL/" style="font-size: 13.88px; color: #71c1c2">MySQL</a> <a href="/tags/PHP/" style="font-size: 16.5px; color: #4dbc6f">PHP</a> <a href="/tags/Rhythmbox/" style="font-size: 13px; color: #7dc3de">Rhythmbox</a> <a href="/tags/SSO/" style="font-size: 13px; color: #7dc3de">SSO</a> <a href="/tags/Servlet/" style="font-size: 13px; color: #7dc3de">Servlet</a> <a href="/tags/Shiro/" style="font-size: 13.88px; color: #71c1c2">Shiro</a> <a href="/tags/Spring/" style="font-size: 13.88px; color: #71c1c2">Spring</a> <a href="/tags/Suse/" style="font-size: 13px; color: #7dc3de">Suse</a> <a href="/tags/Thinking-in-Java/" style="font-size: 19.13px; color: #29b61c">Thinking in Java</a> <a href="/tags/Ubuntu/" style="font-size: 17.38px; color: #41ba53">Ubuntu</a> <a href="/tags/Vim/" style="font-size: 18.25px; color: #35b838">Vim</a> <a href="/tags/VirtualBox/" style="font-size: 13px; color: #7dc3de">VirtualBox</a> <a href="/tags/Vsftpd/" style="font-size: 13px; color: #7dc3de">Vsftpd</a> <a href="/tags/jQuery/" style="font-size: 13px; color: #7dc3de">jQuery</a> <a href="/tags/pam-mysql/" style="font-size: 13px; color: #7dc3de">pam_mysql</a> <a href="/tags/小米/" style="font-size: 13px; color: #7dc3de">小米</a> <a href="/tags/软件/" style="font-size: 15.63px; color: #59bd8b">软件</a>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Archives</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/09/">September 2015</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/08/">August 2015</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/07/">July 2015</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/05/">May 2015</a><span class="archive-list-count">5</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/04/">April 2015</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/03/">March 2015</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/02/">February 2015</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/12/">December 2014</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/11/">November 2014</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/10/">October 2014</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/09/">September 2014</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/08/">August 2014</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/07/">July 2014</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/06/">June 2014</a><span class="archive-list-count">6</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/05/">May 2014</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/04/">April 2014</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/03/">March 2014</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/02/">February 2014</a><span class="archive-list-count">11</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/01/">January 2014</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2013/12/">December 2013</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2013/11/">November 2013</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2013/08/">August 2013</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2013/07/">July 2013</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2013/06/">June 2013</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2013/05/">May 2013</a><span class="archive-list-count">5</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2013/04/">April 2013</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2012/03/">March 2012</a><span class="archive-list-count">1</span></li></ul>
    </div>
  </div>


  
    <div class="widget-wrap">
  <h3 class="widget-title">Calendar</h3>
  <div class="widget">
    <div id="g-calendar" class="g-calendar">
        <span class="g-calendar-prev"></span>
		 
        <span class="g-calendar-back"></span>
        <span class="g-calendar-now"></span>
		 
        <span class="g-calendar-next"></span>
        <div class="g-calendar-hd"></div>
        <div class="g-calendar-tit"></div>
        <div class="g-calendar-bd"></div>
    </div>
  </div>
</div>
<script type="text/javascript">
function LGY_calendar(wrapId, options){
    this.oWrap = this.getId(wrapId);
    this.oHead = this.getByClassName('g-calendar-hd',this.oWrap)[0];
    this.oBody = this.getByClassName('g-calendar-bd',this.oWrap)[0];
    this.oTit = this.getByClassName('g-calendar-tit',this.oWrap)[0];
    this.oPrev = this.getByClassName('g-calendar-prev',this.oWrap)[0];
    this.oNext = this.getByClassName('g-calendar-next',this.oWrap)[0];
    this.oNow = this.getByClassName('g-calendar-now',this.oWrap)[0];
    this.oBack = this.getByClassName('g-calendar-back',this.oWrap)[0];
    this.init();
}
LGY_calendar.prototype = {
    ///////////获取ID元素
    getId:function(id){
        return document.getElementById(id);
    },
    ////////获取css类名元素
    getByClassName:function(className,parent){
        var elem = [],
            node = parent != undefined&&parent.nodeType==1?parent.getElementsByTagName('*'):document.getElementsByTagName('*'),
            p = new RegExp("(^|\\s)"+className+"(\\s|$)");
        for(var n=0,i=node.length;n<i;n++){
            if(p.test(node[n].className)){
                elem.push(node[n]);
            }
        }
        return elem;
    },
    //填充日历
    fillDate:function(year,month){
        //本月份第一天是星期几-为显示上个月的天数做铺垫
        var first_day = new Date(year,month,1).getDay(),
        //如果刚好是星期天，则空出一行（显示上个月的天数）
            first_day = first_day == 0?first_day=7:first_day;
        //本月份最后一天是几号
        var final_date = new Date(year,month+1,0).getDate(),
        //上个月的最后一天是几号
            last_date = new Date(year,month,0).getDate(),
        //剩余的格子数--即排在末尾的格子数
            surplus = 42 - first_day - final_date;
        //设置年的链接
        var yearHead = "<a href='/" + "archives/" + year + "/'>" + year + " "+ "</a>"; 
        //设置年的链接
        var monthHead = "";
        var month1 = month + 1;
        if (month1 < 10) {
            monthHead = "<a href='/" + "archives/" + year + "/" + "0" + month1 + "/'>" + " " + month1 + " " + "</a>";
        } else {
            monthHead = "<a href='/" + "archives/" + year + "/" + month1 + "/'>" + " " + month1 + " " + "</a>";
        }
        //设置表头的日历
        this.oHead.innerHTML = yearHead+'年'+monthHead+'月';
        //填充日历执行
        var html = '';
        //上个月的显示天数
        for(var i=0;i<first_day;i++){
            html+='<span class="g-calendar-grey">'+(last_date-(first_day-1)+i)+'</span>';
        }
        //本月的显示天数
        var postdate = new Date("Fri Aug 28 2015 12:23:08 GMT+0800"); 
        if (true && postdate.getFullYear() == year && postdate.getMonth() == month) { 
            html += '<span>1</span><span>2</span><span>3</span><span>4</span><span>5</span><span>6</span><span>7</span><span>8</span><span>9</span><span><a href="/2015/08/10/java-web/" title="Java Web 笔记">10</a></span><span>11</span><span>12</span><span>13</span><span>14</span><span>15</span><span>16</span><span>17</span><span>18</span><span>19</span><span>20</span><span>21</span><span>22</span><span>23</span><span>24</span><span>25</span><span>26</span><span>27</span><span><a href="/2015/08/28/javascript-reference-type/" title="当天有3篇博客,第一篇:JavaScript 引用类型">28</a></span><span>29</span><span>30</span><span>31</span>';
        } else {
            for(var j=0;j<final_date;j++){        
                html+='<span id="d'+(j+1)+'">'+(j+1)+'</span>';
            }
        }
        //下个月的显示天数
        for(var k=0;k<surplus;k++){
            html+='<span class="g-calendar-grey">'+(k+1)+'</span>';
        }
        //fill
        this.oBody.innerHTML = html;
        // 当前状态
        if(year==this.c_year&&this.c_month==month){
            this.oBody.getElementsByTagName('span')[first_day+this.date-1].className='g-calendar-on';
        }

        // 对所有文章遍历,然后将有文章的日期加上链接,如果文章太多的话,生成页面会很大,去掉了
        
    },
    // next切换
    next:function(){
        var _that = this;
        this.oNext.onclick = function(){
            _that.month++;
            if(_that.month>11){
                _that.month = 0;
                _that.year++;
            }
            // 填充日历
            _that.fillDate(_that.year,_that.month);
        };
    },
    // back 切换
    back:function(){
        var _that = this;
        if(this.oBack != undefined) {
            this.oBack.onclick = function(){
                var postdate = new Date("Fri Aug 28 2015 12:23:08 GMT+0800"); 
                _that.year = postdate.getFullYear();
                _that.month = postdate.getMonth();
                // 填充日历
                _that.fillDate(_that.year,_that.month);
            };
        }
    },
    // now切换
    now:function(){
        var _that = this;
        if(this.oNow != undefined ) {
            this.oNow.onclick = function(){
                var nowDate = new Date(); 
                _that.year = nowDate.getFullYear();
                _that.month = nowDate.getMonth();
                // 填充日历
                _that.fillDate(_that.year,_that.month);
            };
        }
    },
    // prev切换
    prev:function(){
        var _that = this;
        this.oPrev.onclick = function(){
            _that.month--;
            if(_that.month<0){
                _that.month = 11;
                _that.year--;
            }
            // 填充日历
            _that.fillDate(_that.year,_that.month);
        };
    },
    init:function(){
        this.oTit.innerHTML = '<span>日</span><span>一</span><span>二</span><span>三</span><span>四</span><span>五</span><span>六</span>';
        // 获取今天的日历时间
        var now = new Date();
        this.c_year = this.year = now.getFullYear();
        this.c_month = this.month = now.getMonth();
        this.date = now.getDate();
        // 初始化--填充日历
        this.fillDate(this.year,this.month);
        //next切换
        this.next();
        //prev切换
        this.prev();
        //back 切换
        this.back();
        //now 切换
        this.now();
    }
}
new LGY_calendar('g-calendar');
</script>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/2015/09/01/javascript-summary/">JavaScript 总结</a>
          </li>
        
          <li>
            <a href="/2015/08/28/javascript-oop-function-expression-and-async/">JavaScript 面向对象程序设计、函数表达式和异步编程</a>
          </li>
        
          <li>
            <a href="/2015/08/28/javascript-reference-type/">JavaScript 引用类型</a>
          </li>
        
          <li>
            <a href="/2015/08/28/javascript-grammar/">JavaScript 基本语法</a>
          </li>
        
          <li>
            <a href="/2015/08/10/java-web/">Java Web 笔记</a>
          </li>
        
      </ul>
    </div>
  </div>


  
    
<div class="widget-wrap">
  <h3 class="widget-title">Recent Comments</h3>
  <ul class="widget ds-recent-comments" data-num-items="5" data-show-avatars="0" data-show-title="1" data-show-time="1"></ul>
</div>
<!-- 需要多说的公用代码 -->


  

</aside>

        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2015 howiefh<br>
      Powered by <a href="http://zespia.tw/hexo/" target="_blank">Hexo</a> and Theme by <a href="https://github.com/howiefh/hexo-theme-landscape-f" target="_blank" title="Landscape-F">Landscape-F</a>
    </div>
  </div>
</footer>

    </div>
    <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    

<!-- 多说公共JS代码 start (一个网页只需插入一次) -->

<script type="text/javascript">
  var duoshuoQuery = {short_name:"howiefh"};
  (function() {
	var ds = document.createElement('script');
	ds.type = 'text/javascript';ds.async = true;
	ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
	ds.charset = 'UTF-8';
	(document.getElementsByTagName('head')[0] 
		|| document.getElementsByTagName('body')[0]).appendChild(ds);
  })();
</script> 

<!-- 多说公共JS代码 end -->

<!-- 百度分享 start -->

<script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":["mshare","douban","bdysc","sqq","qq","hi","baidu","huaban","youdao","sdo","mail","xg","diandian","fx","copy","print"],"bdPic":"","bdStyle":"1","bdSize":"16"},"share":{},"image":{"viewList":["qzone","tsina","tqq","renren","weixin"],"viewText":"分享到：","viewSize":"16"}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script>

<!-- 百度分享 end -->

<!--
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="/js/jquery.min.js"></script>
-->
<script src="/js/jquery.min.js" type="text/javascript"></script>


  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css" type="text/css">
  <script src="/fancybox/jquery.fancybox.pack.js" type="text/javascript"></script>


<div class="bottom-btn">

	<a class="icon-gotop" href="javascript:void(0)" title="返回顶部"></a>
	<script src="/js/gotop.js" type="text/javascript"></script>
	<!--
	<script src="/js/gotop.js"></script>
	-->


	<a class="icon-toc-toggle" href="javascript:void(0)" title="文章目录"></a>
	<!--
	<script src="/js/toc_aside_toggle.js"></script>
	-->

</div>
<script src="/js/toc_aside_toggle.js" type="text/javascript"></script>


<script src="/js/script.js" type="text/javascript"></script>

  </div>
</body>
</html>
